在Mongoose中使用填充虚拟机时如何聚合? [英] How to aggregate when using populate virtuals in Mongoose?
本文介绍了在Mongoose中使用填充虚拟机时如何聚合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用猫鼬的填充虚拟机.假设我有以下Post模式:
I'm trying to use mongoose's populate virtuals. Let's say I have this Post schema:
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
按评论内容进行过滤:
Now, let's say I wanted to filter by the comment content using aggregate
:
Post.aggregate([
{
$match: {
$or: [{ 'comments.content': /match this content/ }]
}
},
{
$project: { title: 1, comments: 1 }
}
)]
这不起作用,因为尚未填充comments
.有其他选择吗?
This doesn't work because comments
hasn't been populated. Any alternatives?
推荐答案
我认为您可以这样做:
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 }
}
)]`
这篇关于在Mongoose中使用填充虚拟机时如何聚合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文