在Mongoose中使用填充虚拟时如何聚合?

时间:2017-09-28 15:12:54

标签: mongodb mongoose

我正在尝试使用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。任何替代方案?

1 个答案:

答案 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 }
  }
)]`