【问题标题】:Mongoose aggregate returning empty result [duplicate]猫鼬聚合返回空结果[重复]
【发布时间】: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 不需要它们。

标签: node.js mongodb mongoose


【解决方案1】:

$match 函数中的 item.id 是一个字符串,因此您需要将其转换为 ObjectID,如下所示:

$match: { item: mongoose.Types.ObjectId(item.id) }

您可以在 GitHub aggregate 上参考此问题以获取更多详细信息。

【讨论】:

  • 这为我修好了,谢谢!
  • @Chris 太棒了!很高兴为你做到了
  • 救生员。很高兴我找到了您的解决方案。
猜你喜欢
  • 2018-08-22
  • 2017-03-30
  • 2017-12-03
  • 2013-09-08
  • 1970-01-01
  • 2014-05-30
相关资源
最近更新 更多