猫鼬相当于加入..哪里



我有两个模型

Opinion {
_id: string;
creator: string;
teacher: ObjectId;
text: string;
date: Date;
}
Teacher {
_id: string;
name: string;
isVerified: boolean;
}

我需要获得 3 个最新意见,{ 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文档

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 是 $lookup。猫鼬的方法是使用填充,但您必须在模型中提供 ref 键

用于查找用法 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方法更加灵活和可定制

最新更新