在mongoose聚合查询中使用$ match

时间:2017-10-07 08:34:34

标签: mongodb

我正在尝试在mongoose聚合查询中使用$ match。

Feed.aggregate([
          {$match:{"createdBy":'ObjectId("59d79b6ea918cf1e40ee041f")'}},
          {
                "$lookup":
                  {
                    "from": "comments",
                    "localField": "_id",
                    "foreignField": "feedId",
                    "as": "feedComment"
                  }
             }
          ]).exec(function(err, results){
              if(err){
                res.json({"success": false,"errorCode": errorCodes.serverError,"error": err});
              }else{
                if(results == null){
                  res.json({"success": false,"errorCode": errorCodes.dataNotFound,"error": "no record found"})
                }else{
                  res.json({"success": true,"data": results});
                }
              }
           })

它给出了黑色结果数组。

但如果没有$ match,它就会起作用。

Feed集合是:

    {
        "_id" : ObjectId("59d878f67e6ba32c60c7410c"),
        "createdBy" : ObjectId("59d79b6ea918cf1e40ee041f"),
        "feedKeywords" : "school,kids",
        "feedDescription" : "Going to school",
        "feedTitle" : "Going to schoo",
        "updatedAt" : ISODate("2017-10-07T06:49:26.100Z"),
        "createdAt" : ISODate("2017-10-07T06:49:26.100Z"),
        "__v" : 0
}

评论集合就像这样

    {
        "_id" : ObjectId("59d87a737e6ba32c60c7410e"),
        "createdBy" : ObjectId("59d6562dd3c2be2ba452665e"),
        "feedId" : ObjectId("59d878f67e6ba32c60c7410c"),
        "stars" : "3.5",
        "commentText" : "vewr nice",
        "updatedAt" : ISODate("2017-10-07T06:55:47.305Z"),
        "createdAt" : ISODate("2017-10-07T06:55:47.305Z"),
        "__v" : 0
}

1 个答案:

答案 0 :(得分:1)

您已在$ match聚合管道中使用Single Quote作为createdBy的值,因此该值将被视为String,但您的Feed集合中的createdBy数据是一个Object,因此没有检索到数据$ match匹配。

请使用此更正的查询

Feed.aggregate([
          {$match:{"createdBy":new mongoose.Types.ObjectId("59d79b6ea918cf1e40ee041f")}},
          {
                "$lookup":
                  {
                    "from": "comments",
                    "localField": "_id",
                    "foreignField": "feedId",
                    "as": "feedComment"
                  }
             }
          ]).exec(function(err, results){
              if(err){
                res.json({"success": false,"errorCode": errorCodes.serverError,"error": err});
              }else{
                if(results == null){
                  res.json({"success": false,"errorCode": errorCodes.dataNotFound,"error": "no record found"})
                }else{
                  res.json({"success": true,"data": results});
                }
              }
           })