【发布时间】:2018-03-10 09:41:27
【问题描述】:
我正在尝试使用猫鼬的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。有其他选择吗?
【问题讨论】:
-
通常你会使用$lookup来加入cmets然后过滤cmets。
-
@Veeram,没错,就像
$lookup: { from: 'comments', localField: 'comments', foreignField: '_id', as: 'comments' }不幸的是它不会返回任何 cmets -
看起来
localField是一个数组。在$lookup之前尝试{$unwind: "$comments"}看看是否有帮助。$unwind从 3.4 版本开始不需要。 -
我也试过了——它返回一个空数组