首先,我已阅读this stack overflow entry它部分解决了这个问题,但我需要动态添加多个条目,并且无法将答案应用到这个问题。
我有一个带有民意调查的网站(使用express和mongodb驱动程序),我希望用户在提交后能够向民意调查添加其他选项(他们只能添加其他项目,不能编辑预先存在的项目) .
所有选项(可能的答案)都标记为答案
,后跟一个数字(最多 5 个)。
所以在数据库中我们有:
{
"_id": {
"$oid": "58cdf0023cefa56136afb50f"
},
"question": "Who is the best Bob?",
"options": {
"answer1": {
"option": "Bob Dylan",
"votes": 2
},
"answer2": {
"option": "Bob Geldof",
"votes": 0
}
}
}
因此,通过此条目,用户最多可以添加三个附加答案选项。
当我硬编码附加答案名称(例如此数据库示例中的 answer3
)时,我可以更新嵌套的 options
属性。
var toInsert = { options:
{ answer3: { option: 'Bob Saget', votes: 0 },
answer4: { option: 'Bob Marley', votes: 0 } } }
db.collection('questions')
.findOneAndUpdate({"_id": questionId}, {$set : {'options.answer3': [toInsert.answer3]}}, {upsert: true}, (err, result) => {
if (err) return res.send(err)
res.send("worked");
})
编辑:我刚刚意识到他也有一个错误,所以我什至无法正确地对答案进行硬编码。不过,为了清楚起见,我将把它留在这里。
但是我需要做的是使用 1-3 个可能的新选项(取决于用户想要的)动态更新嵌套的 options
对象,并将预先存在的数据保留在 选项
对象。在上面的示例代码中,我想从 toInsert
插入 answer3
和 answer4
。
我对 Node 和 MongoDB 非常陌生,我的“嘿,我可以通过一个 for 循环
”的想法似乎是一个坏主意,即使我能让它工作。
最佳答案
您可以通过将答案文档替换为选项嵌入数组文档来实现您的目标。
{
"_id": {
"$oid": "58cdf0023cefa56136afb50f"
},
"question": "Who is the best Bob?",
"options": [
{
"answer" : "answer1",
"option": "Bob Dylan",
"votes": 2
},
{
"answer" : "answer2",
"option": "Bob Geldof",
"votes": 0
}
]
}
现在,您可以使用 $each
和 $push
运算符轻松将嵌入文档添加到选项中。
db.collection('questions')
.findOneAndUpdate({"_id": questionId}, {$push: { options: { $each: [ { answer: "answer3", option: 'Bob Saget', votes: 0 },{ answer: "answer4", option: 'Bob Marley', votes: 0 } ] } } } )
关于node.js - 使用多个值部分更新嵌套对象 Express.js MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42887387/