Javascript 转换为ObjectId的值“失败”;xxx“;在路径上“_id";当与猫鼬聚集时
我正在尝试使用基于我的mongoose模型的聚合。我想根据categoryId汇总金额。但当试图通过路由url访问时,我遇到了这个错误。(对于路径“\u id”处的值“test”,转换为ObjectId失败) test.js中的我的猫鼬模型(模型) 我的控制器testController-Javascript 转换为ObjectId的值“失败”;xxx“;在路径上“_id";当与猫鼬聚集时,javascript,node.js,mongodb,mongoose,aggregation-framework,Javascript,Node.js,Mongodb,Mongoose,Aggregation Framework,我正在尝试使用基于我的mongoose模型的聚合。我想根据categoryId汇总金额。但当试图通过路由url访问时,我遇到了这个错误。(对于路径“\u id”处的值“test”,转换为ObjectId失败) test.js中的我的猫鼬模型(模型) 我的控制器testController- var Test = require('../models/test'); function aggTest(req,res){ Test.aggregate([{ $group:{
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"
}
有什么建议吗 我的回答中有两个问题。感谢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 });
});
可能是因为聚合管道采用了两个参数
$match
和$group
?我使用mongoose来聚合带有wherecondition
的内容没有问题。根据这里给出的示例,他们使用了$group而没有$match。该错误非常“mongoose特有”,因此我怀疑您没有显示代码。我认为您正在尝试将聚合结果“转换”到Mongoose对象中。.aggregate()
命令本身只返回“普通对象”。这是有意义的,因为“通常”聚合的结果对象与原始集合的模型完全不同。
Test.aggregate([
{ $group: {
_id:"$categoryId",
totalAmount:{$sum: "$amount"}
}}
], function (err, result) {
if (err) {
console.log(err);
return;
}
console.log(result);
res.json({ data:result });
});