【发布时间】: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