$match 在 mongoose 5.6+ 中找不到 objectID

$match not finding objectID in mongoose 5.6+

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

这是我的测试代码。

函数 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));


});

}

试试这个:

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));


});
}
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));


});
}