我正在尝试使用mongoose的populate virtuals。假设我有这个Post模式:
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
content: {
type: String,
required: true
}
});
postSchema.virtual('comments', {
ref: 'Comment',
foreignField: '_id',
localField: 'post'
});
现在,假设我想使用aggregate
Post.aggregate([
{
$match: {
$or: [{ 'comments.content': /match this content/ }]
}
},
{
$project: { title: 1, comments: 1 }
}
)]
这不起作用,因为尚未填充comments
。任何替代方案?
答案 0 :(得分:1)
我认为你可以这样做:
Post.aggregate([
{
$lookup:{
from:"comments",
localField:"_id",
foreignField:"post",
as:"comments"
},
$unwind:{
"$comments"
},
$match: {
$or: [{ 'comments.content': /match this content/ }]
}
},
{
$project: { title: 1, comments: 1 }
}
)]`