首页 > 解决方案 > 聚合猫鼬 nodejs $match 不起作用

问题描述

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 alliancealliances收藏中过滤。

AllianceMember _id user_id ally_id

Alliance _id title leader

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

我得到的错误$match: Arguments must be aggregate pipeline operators

标签: node.jsmongodbmongooseaggregation-framework

解决方案


$lookup你把两个和$match舞台都搞砸了。而且你也没有把你的ally_idfromString转换成 mongooseObjectId

它应该是这样的

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

推荐阅读