unable to use $match operator for mongodb/mongoose aggregation with ObjectId

后端 未结 4 1719
攒了一身酷
攒了一身酷 2020-12-16 15:03

Relatively Simple Scenario:

I have this Voucher object which has a user property (of type ObjectId). I want to get the sum of

相关标签:
4条回答
  • 2020-12-16 15:55
    var aggregate  = [
    {
                    $match: {
                        'lenderId': new mongoose.Types.ObjectId(req.user),
                        '_disbursed': true
                    }
                },
                {
                    $unwind:'$emi'
                },
                {
                    $match: {
                        'emi._settled': false,
                    }
                }
    ];
    
    0 讨论(0)
  • 2020-12-16 15:58

    use toString() method.

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

    0 讨论(0)
  • 2020-12-16 16:00

    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.

    0 讨论(0)
  • 2020-12-16 16:03

    When using the find method or findById the query can be only:

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

    When using aggregate the query need a cast

    var mongoose = require('mongoose');
    var query = {
        $or: [
            {'_sender':new mongoose.Types.ObjectId(decoded._id)},
            {'_recipient':new mongoose.Types.ObjectId(decoded._id)}
        ]
    };
    
    0 讨论(0)
提交回复
热议问题