Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 324
Tyler Shaddix Avatar asked Apr 30 '13 23:04

Tyler Shaddix


People also ask

What is Mongoose types ObjectId?

Types. ObjectId . A SchemaType is just a configuration object for Mongoose. An instance of the mongoose. ObjectId SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.

What is $project in MongoDB?

The $project takes a document that can specify the inclusion of fields, the suppression of the _id field, the addition of new fields, and the resetting of the values of existing fields. Alternatively, you may specify the exclusion of fields. Specifies the inclusion of a field.

What is $EXPR in MongoDB?

$expr can build query expressions that compare fields from the same document in a $match stage. If the $match stage is part of a $lookup stage, $expr can compare fields using let variables. See Perform Multiple Joins and a Correlated Subquery with $lookup for an example.

What does aggregate do in mongoose?

Mongoose's aggregate() function returns an instance of Mongoose's Aggregate class. Aggregate instances are thenable, so you can use them with await and promise chaining. The Aggregate class also supports a chaining interface for building aggregation pipelines.


1 Answers

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.

like image 163
Tyler Shaddix Avatar answered Sep 21 '22 12:09

Tyler Shaddix