最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

运维笔记admin8浏览0评论

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

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

我知道用户的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 ]
}
});
回答如下:

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

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

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

Users.findOne({"_id": req.user._id, "groceryList.name": ingredients.name[i] })
发布评论

评论列表(0)

  1. 暂无评论