如何从数组字段与mongoose获得特定的对象

给定一个像这样的模式:

UserSchema = new Schema({ name: String, donations: [ { amount: Number, charity: { type: Schema.Types.ObjectId, ref: 'charity' } } ] }); 

我有用户和非营利组织的(string)ID,我想获得用户捐赠的金额。 我用lodash使用这个查询:

 User.findOne({ _id: userId }, function(err, user) { var amount = _.find(user.donations, {charity: charityId}); console.log("the amount is: ", amount); }); 

这里金额返回undefined即使它不应该也猜测我不应该使用lodash 。 给定一个特定的userIdcharityId ,获得捐赠金额的正确方法是什么?

这与我链接到的可能重复非常相似,因为您可以在不使用lodash的情况下执行此操作:

 User.findOne({ _id: userId, 'donations.charity': charityId }, { 'donations.$': 1 }, function(err, user) { console.log("the amount is: ", user.donations[0].amount); });