Sanath
Sanath

Reputation: 4886

Cast to ObjectId failed for value "xxx" at path "_id" when aggregating with mongoose

I am trying to use aggregation based on my mongoose model. I want to aggregate amounts based on categoryId. But when trying to access via routes url, I am getting this error. (Cast to ObjectId failed for value "test" at path "_id").

my mongoose model in test.js (MODEL)

var ObjectId = Schema.ObjectId;

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

My controller testController -

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

Routes mapping

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

Error that-

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

Any suggestions?

Upvotes: 0

Views: 1583

Answers (1)

Sanath
Sanath

Reputation: 4886

There were 2 issues in my answer. Thanks for Blake Seven for pointing me in to the right direction. I didn't have a proper return to return response and my callback function was not correct. The corrected code is here.

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

Upvotes: 2

Related Questions