聚合猫鼬nodejs $ match不起作用

时间:2018-11-24 11:53:12

标签: node.js mongodb mongoose aggregation-framework

AllianceMember.aggregate([{
                $match : { ally_id : alliance._id } ,
                $lookup:
                  {
                    from: 'users',
                    localField: 'user_id',
                    foreignField: '_id',
                    as: 'users'
                  }
 }]).then((members) => {});

所以基本上我想要实现的是获取members that are in alliance,然后将它们与users表进行汇总。这部分代码有效。但是现在我需要从members that are in alliance集合中过滤alliances

AllianceMember _id user_id ally_id

Alliance _id title leader

我需要在联盟页面中显示ally_id等于alliance_id的用户。没有$match功能,我会在每个联盟中都出现所有成员。

$match: Arguments must be aggregate pipeline operators出现的错误

1 个答案:

答案 0 :(得分:0)

您已经弄乱了$lookup$match阶段。 而且您也没有将ally_idString投射到猫鼬ObjectId

应该是

db.aggregate([
  { "$match": { "ally_id": mongoose.Types.ObjectId(alliance._id) } },
  { "$lookup": {
    "from": "users",
    "localField": "user_id",
    "foreignField": "_id",
    "as": "users"
  }}
])