$ match在猫鼬5.6+中找不到objectID

时间:2018-07-13 13:48:01

标签: match aggregation objectid

我之前已经检查过有关该主题的各种帖子,但没有任何建议对我有用。我已经看到这些建议在猫鼬5.0中不起作用。我正在使用猫鼬5.6。我尝试了find(),它正在工作。但我需要聚合fm才能扩展使用。大多数建议是关于转换我使用过的记录id mongoose.Types.ObjectId()的。但没有使我工作。请帮助

这是我的测试代码。

function totalActualSale(recordId){

Record.aggregate([
    {  
      $match : {
        '_id':mongoose.Types.ObjectId(recordId),
      }
    },
    {
        $unwind:  { "path": '$SalesList'}
    },
    { $group:
        {_id:
            {
                item:"$SalesList.item",
            },
            pqty: { $sum: '$SalesList.pqty' },
        }
    },
    ], function (err, purc) {

        console.log("\nStock:"+ JSON.stringify(purc));


});

}

2 个答案:

答案 0 :(得分:0)

尝试:

function totalActualSale (recordId) {

Record.aggregate([
    {  
      $match : {
        '_id':new mongoose.mongo.ObjectId(recordId),
      }
    },
    {
        $unwind:  { "path": '$SalesList'}
    },
    { $group:
        {_id:
            {
                item:"$SalesList.item",
            },
            pqty: { $sum: '$SalesList.pqty' },
        }
    },
    ], function (err, purc) {

        console.log("\nStock:"+ JSON.stringify(purc));


});
}

答案 1 :(得分:0)

Actually the actual issue was just reverse. the 'recordId' passed to the function was the ObjectID of a record. so, when comparing we should convert that into string. recordId.toString().  So the solution is 

function totalActualSale (recordId) {

Record.aggregate([
    {  
      $match : {
        '_id':recordId.toString(),
      }
    },
    {
        $unwind:  { "path": '$SalesList'}
    },
    { $group:
        {_id:
            {
                item:"$SalesList.item",
            },
            pqty: { $sum: '$SalesList.pqty' },
        }
    },
    ], function (err, purc) {

        console.log("\nStock:"+ JSON.stringify(purc));


});
}
相关问题