猫鼬:查找嵌套的ID?

时间:2020-04-22 18:03:05

标签: node.js mongoose

很抱歉,如果这是一个重复性的问题,但是经过数小时的上网搜索后,我还没有找到解决方法:(。我有一个用于存储任务的数据库(一个待办事项列表应用程序),然后还有另一个这样您就可以使用不同的待办事项创建自定义待办事项列表...

此数据库存储具有特定待办事项的其他模式的名称和项目数组。

const listSchema = {
    name: String,
    items: [itemSchema]
}

数据库如下:

[
  {
    _id: 5ea083694f1d7d0db432b939,
    name: 'home',
    items: [ [Object], [Object] ],
    __v: 2
  }
]

,在items数组中看起来像这样:

[
  { _id: 5ea083764f1d7d0db432b93a, name: 'some todo', check: false },
  {
    _id: 5ea08391ab923b36780429ee,
    name: 'some other todo',
    check: false
  }
]

我想做的是通过项数组中的特定ID查找和更新,我有变量

 const id = req.body.check // in a for loop and gets id of the specific item 
 const titleName = req.body.titleName; // gets the title name of the parent object of the items array

,它需要使用titleName和id进行查找,以便我可以更新“ check:false”,使其为“ check:true”

。 。

找到解决方案:

 List.updateOne({"items._id" : id}, {"$set": {"items.$.check": true}})

1 个答案:

答案 0 :(得分:0)

您可以使用猫鼬的findOneAndUpdate(filter,update)

const id = req.body.id;
 const titleName = req.body.titleName; 
collectionName.findOneAndUpdate({"items.id": id, "name": titleName}, {"check": true})