代码之家  ›  专栏  ›  技术社区  ›  Sanath

在与mongoose聚合时,在路径“_id”处的值“xxx”转换为ObjectId失败

  •  0
  • Sanath  · 技术社区  · 11 年前

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

    我的猫鼬模型在测试中。js(型号)

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

    我的控制器测试控制器-

    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"
    }
    

    有什么建议吗?

    1 回复  |  直到 9 年前
        1
  •  2
  •   Sanath    11 年前

    我的回答有两个问题。感谢Blake Seven为我指明了正确的方向。我没有正确的返回到返回响应,回调函数也不正确。 更正的代码在这里。

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