确定用户的嵌入式文档数组中是否存在值

问题描述 投票:0回答:1

我知道用户的ID,我想知道他们的shoppingList中是否有与"name" = "foo"匹配的值。这是我当前的查询,但它返回结果,即使名称不存在,我假设因为其中一个值存在。如果两个值都为真,我如何只返回结果?

User.findOne( {"_id": req.user._id},{"groceryList": {"$elemMatch": {"name": ingredients.name[i]}}}, function(err, result) {
        if(err) {
                console.log(err);
            }
            else if(result) {
                console.log(result);
            }
    })

用户架构:

var groceryListSchema = mongoose.Schema({
quantity: { type: Number, required: true },
measurement: { type: String, required: true },
name: { type: String, required: true }
});

var userSchema = new mongoose.Schema({
username: String,
password: String,
recipes: [
  {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Recipe'
  }
],
groceryList: {
type: [ groceryListSchema ]
}
});
javascript node.js mongodb mongoose
1个回答
1
投票

第二个参数应该是查询的一部分。

User.findOne({"_id": req.user._id, "groceryList": {"$elemMatch": {"name": ingredients.name[i]}}})

如上所述,写起来会更简单:

Users.findOne({"_id": req.user._id, "groceryList.name": ingredients.name[i] })
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.