【问题标题】:Cast to ObjectId failed for value "xxx" at path "_id" when aggregating with mongoose与猫鼬聚合时,路径“_id”处的值“xxx”转换为 ObjectId 失败
【发布时间】:2015-11-07 04:25:24
【问题描述】:

我正在尝试使用基于我的猫鼬模型的聚合。我想根据 categoryId 汇总金额。但是当尝试通过路由 url 访问时,我收到了这个错误。 (对于路径“_id”处的值“test”,转换为 ObjectId 失败)。

我在 test.js 中的猫鼬模型(模型)

var ObjectId = Schema.ObjectId;

var test = new Schema({
    //testId:ObjectId,
    testName: String,
    amount:Number,
    categoryId:String
});
module.exports = mongoose.model('test', test);

我的控制器 testController -

var Test = require('../models/test');
function aggTest(req,res){
    Test.aggregate([{
        $group:{
            _id:"$categoryId",
            totalAmount:{$sum: "$amount"}
        }
    }],function(err,result){
        console.log(result);
    });
}

路线映射

router.get('/test',testController.aggTest);

错误那个-

{
  message: "Cast to ObjectId failed for value "test" at path "_id""
  name: "CastError"
  type: "ObjectId"
  value: "test"
  path: "_id"
}

有什么建议吗?

【问题讨论】:

  • 会不会是因为聚合管道需要$match$group两个参数?我可以使用 mongoose 来聚合 wherecondition 的东西
  • docs.mongodb.org/manual/tutorial/aggregation-zip-code-data-set 根据此处给出的示例,他们使用了 $group 而没有 $match
  • 该错误非常“特定于猫鼬”,所以我怀疑您没有显示代码。我认为您正在尝试将聚合结果“投射”到 Mongoose 对象中。 .aggregate() 命令本身只返回“普通对象”。这是有道理的,因为“通常”来自聚合的结果对象看起来与原始集合的模型完全不同。

标签: javascript node.js mongodb mongoose aggregation-framework


【解决方案1】:

我的回答中有两个问题。感谢布莱克七号为我指明了正确的方向。我没有正确的返回来返回响应,并且我的回调函数不正确。 更正的代码在这里。

Test.aggregate([
        { $group: {
            _id:"$categoryId",
            totalAmount:{$sum: "$amount"}
        }}
    ], function (err, result) {
        if (err) {
            console.log(err);
            return;
        }
        console.log(result);
        res.json({ data:result });
    });

【讨论】:

    猜你喜欢
    • 2016-11-11
    • 2020-05-20
    • 2021-04-21
    • 1970-01-01
    • 2021-02-21
    • 2014-06-20
    • 2017-05-19
    • 2017-11-10
    • 2019-05-02
    相关资源
    最近更新 更多