如何使用猫鼬从数组字段中获取特定对象

wem*_*eit 1 mongoose mongodb node.js lodash

给定这样的模式:

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

我有一个用户和一个非营利组织的(字符串)ID,我想获取用户捐赠的金额。我在lodash中使用此查询:

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

在这里,金额返回未定义的值,即使它也不应该猜我不必使用lodash。给定特定userId和的捐赠金额,正确的方法是charityId什么?

Joh*_*yHK 6

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

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