如何使用mongoose [duplicate]从数组字段中获取特定对象

时间:2023-02-09 08:48:17

This question already has an answer here:

这个问题在这里已有答案:

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:

我有一个用户和非营利组织的(字符串)ID,我想获得用户捐赠的金额。我在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?

这里金额返回undefined,即使它不应该也猜测我不应该使用lodash。在给定特定userId和charityId的情况下,获得捐赠金额的正确方法是什么?

1 个解决方案

#1


2  

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

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

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

#1


2  

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

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

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