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
?
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.
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.
$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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With