Failed to use the $ match operator to aggregate mongodb / mongoose with ObjectId

A relatively simple scenario:

I have this Voucher object that has a user property (of type ObjectId ). I want to get the sum of all the voucher values ​​for one user. Here is my current strategy that 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 a match for the user identifier and leaving the expires field will return results. So the question is getting wrong with matching on user ?

+4
source share
3 answers

Turns out casting ObjectId seems to have been a problem. It was started using the object identifier of the mongoose.Schema.Types.ObjectId schema type, when it was supposed to be just a pure ObjectId mongoose.Types.ObjectId .

+41
source

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

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

When using an aggregate, a query requires listing

 var mongoose = require('mongoose'); var query = { $or: [ {'_sender':new mongoose.Types.ObjectId(decoded._id)}, {'_recipient':new mongoose.Types.ObjectId(decoded._id)} ] }; 
+7
source
 var aggregate = [ { $match: { 'lenderId': new mongoose.Types.ObjectId(req.user), '_disbursed': true } }, { $unwind:'$emi' }, { $match: { 'emi._settled': false, } } ]; 
+1
source

All Articles