Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
952 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...