1

Given a schema like this:

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

I have the (string) ids of a user and of a nonprofit and I want to get the amount the user donated. Im using this query with lodash:

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

Here the amount returns undefined even though it shouldn't also im guessing i shouldn't have to use lodash. What's the right way to get to the amount donated given a specific userId and charityId?

wemadeit
  • 467
  • 6
  • 11
  • not really because I am filtering after selecting and it doesnt work probably because charity is an Object and im searching on a string id – wemadeit Jul 19 '14 at 02:59
  • OK, I'm a bit unsure what you're trying to do because you're passing `user.shares` to `_.find` but `shares` doesn't appear in your schema. Should that be `user.donations`? – JohnnyHK Jul 19 '14 at 03:07
  • 1
    So how does the referenced question not help you? The point there is that you can process this in the MongoDB server rather than filter in your node client code. – Neil Lunn Jul 19 '14 at 03:27

1 Answers1

8

This is pretty similar to the possible duplicate I linked to, as you can do this without using lodash as:

User.findOne({
  _id: userId,
  'donations.charity': charityId
}, {
  'donations.$': 1
}, function(err, user) {
  console.log("the amount is: ", user.donations[0].amount);
});
JohnnyHK
  • 270,398
  • 59
  • 567
  • 434
  • is the [0] in this --> console.log("the amount is: ", user.donations[0].amount); correct because of 'donations.$':1? – wemadeit Jul 19 '14 at 03:39
  • @user3854950 Right, the [`$`](http://docs.mongodb.org/manual/reference/operator/projection/positional/#proj._S_) limits that array field to contain just the first matching element. – JohnnyHK Jul 19 '14 at 03:44
  • This is great! Worked out fine thanks :) – pxtvr Aug 12 '16 at 23:31