【问题标题】:How to aggregate when using populate virtuals in Mongoose?在 Mongoose 中使用填充虚拟时如何聚合?
【发布时间】: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 版本开始不需要。
  • 我也试过了——它返回一个空数组

标签: mongodb mongoose


【解决方案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 }
  }
)]`

【讨论】:

  • 事实证明,我将本地和外国领域颠倒了。我刚刚更新了你的答案。谢谢!
猜你喜欢
  • 2018-05-20
  • 2020-12-08
  • 2017-10-29
  • 2019-04-23
  • 2020-10-14
  • 2019-06-17
  • 2017-12-06
  • 1970-01-01
  • 2018-10-20
相关资源
最近更新 更多