17

相对简单的场景:

我有这个Voucher对象,它有一个user属性(类型ObjectId)。我想获取单个用户的所有凭证值的总和。这是我当前的策略,它返回一个空数组:

Voucher.aggregate [
    { $match : { user : new ObjectId(user_id), expires : { $gt : new Date() } } }
    { $group : { _id : null, sum : { $sum : '$value' } } }
], (err, result)->

    console.log err
    console.log result

删除 id 的匹配项user并离开该expires字段将返回结果。所以问题变成了比赛有什么问题user

4

4 回答 4

58

Turns out the casting of the ObjectId seemed to be the issue. It was being cast using the Schema type Object Id mongoose.Schema.Types.ObjectId when it needed to be just a pure ObjectId mongoose.Types.ObjectId.

于 2013-05-01T04:54:42.933 回答
20

使用 find 方法或 findById 时,查询只能是:

var query = {
    $or: [
        {'_sender':req.body._id},
        {'_recipient':req.body._id}
    ]
};

使用聚合时,查询需要强制转换

var mongoose = require('mongoose');
var query = {
    $or: [
        {'_sender':new mongoose.Types.ObjectId(decoded._id)},
        {'_recipient':new mongoose.Types.ObjectId(decoded._id)}
    ]
};
于 2015-03-01T17:20:12.550 回答
14
var aggregate  = [
{
                $match: {
                    'lenderId': new mongoose.Types.ObjectId(req.user),
                    '_disbursed': true
                }
            },
            {
                $unwind:'$emi'
            },
            {
                $match: {
                    'emi._settled': false,
                }
            }
];
于 2017-05-19T08:29:15.410 回答
2

使用 toString() 方法。

{ $match : { user : user_id.toString() , expires : { $gt : new Date() } } }

于 2018-10-14T15:02:27.353 回答