[英]Mongoose equivalent of JOIN … WHERE
I've got two models我有两个模型
Opinion {
_id: string;
creator: string;
teacher: ObjectId;
text: string;
date: Date;
}
Teacher {
_id: string;
name: string;
isVerified: boolean;
}
I need to get 3 latest Opinions WHERE { teacher.isVerified: true }
我需要获得 3 个最新意见 WHERE
{ teacher.isVerified: true }
I tried我试过了
const newOpinions = await Opinion.find(
null,
"creator teacher text",
{
sort: {
date: -1,
},
}).populate(
{
path: 'teacher',
model: 'Teacher',
select: 'name',
match: {
isVerified: true,
},
}
).limit(3);
but (after short analysis) it works as designed - I'm getting 3 latest opinions, no matter if teachers is verified or not (in teacher field I'm getting null
if it's not verified)但是(经过简短分析)它按设计工作 - 我得到 3 个最新意见,无论教师是否经过验证(在教师领域,如果未经验证,我将得到
null
)
Can anyone try to point me in the right direction?任何人都可以尝试指出我正确的方向吗? I think maybe something with
Model.aggregate()
.我认为可能与
Model.aggregate()
。
This is one way to do it.这是一种方法。 With this one you will filter the teachers first.
有了这个,您将首先过滤教师。 Please also consult
$lookup
documentation另请参阅
$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
}])
The equivalent of join in mongodb is $lookup. mongodb 中的 join 等价物是 $lookup。 A mongoose way is to use populate but you'll have to provide ref key in your model
mongoose 方法是使用填充,但您必须在 model 中提供参考密钥
For lookup usage https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/对于查找用法https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
Mongoose Ref Mongoose 参考
Opinion {
_id: string;
creator: string;
teacher: {
type: Schema.Types.ObjectId, ref: 'Teacher'
},
text: string;
date: Date;
}
Teacher {
_id: string;
name: string;
isVerified: boolean;
}
The $lookup approach is much more flexible and customizable $lookup 方法更加灵活和可定制
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.