猫鼬相当于 JOIN ... WHERE

Mongoose equivalent of JOIN ... WHERE

我有两个模型

Opinion {
  _id: string;
  creator: string;
  teacher: ObjectId;
  text: string;
  date: Date;
}

Teacher {
  _id: string;
  name: string;
  isVerified: boolean;
}

我需要获得 3 个最新意见 WHERE { teacher.isVerified: true }

我试过了

    const newOpinions = await Opinion.find(
      null,
      "creator teacher text",
      {
        sort: {
          date: -1,
        },
      }).populate(
        {
          path: 'teacher',
          model: 'Teacher',
          select: 'name',
          match: {
            isVerified: true,
          },
        }
      ).limit(3);

但是(经过简短分析)它按设计工作 - 我得到了 3 个最新意见,无论教师是否经过验证(在教师领域我得到 null 如果它没有经过验证)

谁能给我指出正确的方向?我想也许 Model.aggregate().

这是一种方法。有了这个,您将首先过滤教师。另请咨询$lookup documentation

Teacher.aggregate([{
  $match: { isVerified: true }
}, {
  $lookup: {
    from: 'opinions' // assume you have collection named `opinions` for model `Opinion`,
    localField: '_id', // join teacher._id ...
    foreignField: 'teacher', // ... with opionion.teacher
    as: 'opinions'
  } // from here you well get verified teachers with embedded opinions, 
// further stages are optional. We will modify the shape of output to be opinions only
}, { 
  $unwind: '$opinions' // spread out opinions array into separate documents
}, {
  $replaceRoot: '$opinions' // replace the root document with opinion only
}])

mongodb 中的 join 等价于 $lookup。猫鼬的方法是使用 populate 但你必须在你的模型中提供 ref key

用于查找用途 https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

猫鼬参考

Opinion {
  _id: string;
  creator: string;
  teacher: {
      type: Schema.Types.ObjectId, ref: 'Teacher'
  },
  text: string;
  date: Date;
}

Teacher {
  _id: string;
  name: string;
  isVerified: boolean;
}

$lookup 方法更加灵活和可定制