$addFields $size 属性总是返回零 - 猫鼬

时间:2021-04-10 08:18:46

标签: javascript node.js mongodb mongoose

嗨,我在聚合查询中添加了 $addFields 属性,文档的 $size 总是返回 0。这是我的表和查询

桌柱:

{
_id: 1,
text: 'some text',
}

表格评论:

{
_id: 1,
text: 'comment text',
postId: 1
}

总的来说,我有以下内容

let aggregateDataQuery = [
  {
    $lookup: {
      from: 'comments',
      localField: '_id',
      foreignField: 'postId',
      as: 'numberOfComments',
    },
  },
  {
    $addFields: {numberOfComments: { $size: { $ifNull: ['$numberOfComments', []] } }},
  },
];

此查询总是导致 numberOfComments: 0。我确信有针对 postId 1 的评论,但结果始终为零。知道我在这里缺少什么。谢谢

1 个答案:

答案 0 :(得分:0)

您好,from 中的子句 $lookup 留在集合中比您想加入的要多。 起始集合必须是 posts 集合。 所以你应该用 comments 代替 posts$size 属性不起作用,因为加入未加入。

代码必须是这样的:

let aggregateDataQuery = [
  {
    $lookup: {
      from: 'comments',
      localField: '_id',
      foreignField: 'postId',
      as: 'numberOfComments',
    },
  },
  {
    $addFields: {numberOfComments: { $size: { $ifNull: ['$numberOfComments', []] } }},
  },
];
Posts.aggregate(aggregateDataQuery);