mongodb - 通过 ID 更新 Mongoose 中的数组元素
问题描述
我想修改单个 MongoDB 文档中的数组元素,但我不知道如何。这是我拥有的示例文档。
{
"_id": "5eefbb77dcc4af0255ef52c6",
"question": "How are you?",
"answers": [
{
"count": 5,
"_id": "5eefbb77dcc4af0255ef52c7",
"body": "Fantastic"
},
{
"count": 20, // I want to increment this by 1
"_id": "5eefbb77dcc4af0255ef52c8",
"body": "Meh"
},
{
"count": 100,
"_id": "5eefbb77dcc4af0255ef52c9",
"body": "Bad"
}
],
"createdAt": "2020-06-21T19:56:39.336Z",
"updatedAt": "2020-06-21T19:56:39.336Z",
"__v": 0
},
我目前正在尝试使用 document.FindByIdAndUpdate(),但我不知道如何使用。任何帮助表示赞赏!
解决方案
这对你来说应该很好:
Model.findOneAndUpdate({ _id: "5eefbb77dcc4af0255ef52c6", "answers._id": "5eefbb77dcc4af0255ef52c8" },
{ $inc: { "answers.$.count": 1 },
{ new: true }
})
.then((item) => {
console.log(item)
}, (e) => {
console.log(e)
})
上面的查询将找到确切的答案,然后将计数加 1。
推荐阅读
- react-native - 使用 '--warning-mode all' 显示个别弃用警告
- html - 从模板中获取数据以发送电子邮件
- c# - 我只需要添加 4 个对象的属性
- android - 是否可以在 Firebase 中更改自动选择的用户属性
- java - Postman 在 SOAP 响应中返回 Null 值
- xcode - 如何从 C# 代码修改 XIB 中的属性
- ansible - Ansible OpenShift shell 命令失败,但在 Ansible 之外工作
- ansible - ansible 可以使用列表和字典中的公共值创建字典吗?
- razor - 构建具有 N 列、2 行、容器最大高度的 CSS 网格
- python - 在多个文件/目录中搜索字符串,然后打印文本文件的内容