【发布时间】:2015-08-04 07:16:34
【问题描述】:
我在处理 mongoose 聚合请求时遇到问题。
这有点让我发疯,因为我在任何地方都找不到解决方案。我将非常感谢任何支持。
架构:
var EvalSchema = new Schema({
modified: {type: Date, default: Date.now},
created : {type: Date, default: Date.now},
username: {type: String, required: true},
item: {type: String, required: true},
criteria: [{
description: {
type: String
},
eval: {
type: Number
}
}]
});
mongoose.model('Eval', EvalSchema);
我正在使用聚合来计算给定项目的每个标准的评估总和。
Eval.aggregate([{
$match: {
item: item.id
}
}, {
$unwind: "$criteria"
}, {
$group: {
_id: "$criteria.description",
total: {
$sum: "$criteria.eval"
},
count: {
$sum: 1
}
}
}, {
$project: {
total: 1,
count: 1,
value: {
$divide: ["$total", "$count"]
}
}
}], function(err, result) {
if (err) {
console.log(err);
}
console.log(result);
});
结果总是空的......
我正在记录应用程序中所有 mongoose 触发的查询。当我在 Mongodb 中运行查询时,它会返回正确的结果。
coll.aggregate([{
'$match': {
item: 'kkkkkkkkkkk'
}
}, {
'$unwind': '$criteria'
}, {
'$group': {
_id: '$criteria.description',
total: {
'$sum': '$criteria.eval'
},
count: {
'$sum': 1
}
}
}, {
'$project': {
total: 1,
count: 1,
value: {
'$divide': ['$total', '$count']
}
}
}])
结果:
{
result: [{
"_id": "Overall satisfaction",
"total": 4,
"count": 1,
"value": 4
}, {
"_id": "service",
"total": 3,
"count": 1,
"value": 3
}, {
"_id": "Quality",
"total": 2,
"count": 1,
"value": 2
}, {
"_id": "Price",
"total": 1,
"count": 1,
"value": 1
}],
ok: 1
}
模型引用了正确的集合。
谢谢你:)
【问题讨论】:
-
你检查过来自
item.id的值吗? -
是的,我做到了。它包含正确的值。 :(
-
检查item.id的类型。也许它不是一个字符串。
-
item.id的类型是字符串... :(
-
对于任何最终来到这里的迷失灵魂,在我的情况下,问题是我一直在
match中将 id 作为 Strings 传递。当我们将 id 作为 ObjectID 传递时,聚合起作用了。事实证明,聚合需要 ObjectID,即使 find 不需要它们。