Tyler Shaddix
Tyler Shaddix

Reputation: 1641

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

Relatively Simple Scenario:

I have this Voucher object which has a user property (of type ObjectId). I want to get the sum of all voucher values for a single user. Here is my current strategy, which returns an empty array:

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

Removing the match for the user id, and leaving the expires field will return results. So the question becomes what is wrong with the match on user?

Upvotes: 17

Views: 23962

Answers (4)

Sameera
Sameera

Reputation: 83

use toString() method.

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

Upvotes: 2

Ankit Kumar Rajpoot
Ankit Kumar Rajpoot

Reputation: 5610

var aggregate  = [
{
                $match: {
                    'lenderId': new mongoose.Types.ObjectId(req.user),
                    '_disbursed': true
                }
            },
            {
                $unwind:'$emi'
            },
            {
                $match: {
                    'emi._settled': false,
                }
            }
];

Upvotes: 12

Fabius
Fabius

Reputation: 211

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)}
    ]
};

Upvotes: 21

Tyler Shaddix
Tyler Shaddix

Reputation: 1641

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.

Upvotes: 63

Related Questions