我正在尝试更新 mongoDB 中包含嵌套数组的文档。
情况如下:
我有一个 newsItem 模型,它可以包含一个 poll 对象。这个投票对象有:title、totalVotes 和 options。option 是一个对象数组,这些对象包含:optionName 和 optionVotes。在这些对象中的每一个中。optionVotes 是一个数组,其中包含对他们进行投票的用户的 ID。(因为我想跟踪谁对什么投票以及有多少我想防止投票两次)
所以它应该看起来像这样:
{
"_id" : ObjectId("5bb7487727430319f5c18495"),
"poll" : {
"totalVotes" : 0,
"title" : "test",
"options" : [
{
"optionName" : "Burgers",
"optionVotes" : []
},
{
"optionName" : "Pizza",
"optionVotes" : []
},
{
"optionName" : "Fish",
"optionVotes" : []
},
{
"optionName" : "BBQ",
"optionVotes" : []
},
{
"optionName" : "Soup",
"optionVotes" : []
},
{
"optionName" : "Pasta",
"optionVotes" : []
}
]
}
}
我现在要做的是,每当 api 路由 /news/votes/:id 被调用时,它都会用 :id 更新新闻项目并将用户 ID 放入给定的投票选项中。(在正文中)所以在请求中我有:用户 ID 和投票的 optionName
这是我目前得到的,但对我不起作用:
exports.vote = (req, res) => {
News.findOneAndUpdate({ _id: req.params.id }).exec((err, newsItem) => {
let tempItem = newsItem
for (let i = 0; i < tempItem.poll.options.length; i++) {
if (tempItem.poll.options[i].optionName === req.body.optionName) {
tempItem.poll.options[i].optionVotes.push(req.user._id)
}
}
console.log(tempItem.poll.options[0])
tempItem.save(err => {
if (!err) {
return res.status(200).send()
}
})
})
}
奇怪的是,当我这样做时:
tempitem.poll.title = '新标题' tempitem.save()
那么标题确实会在数据库中更新!代码中的 console.log 确实输出了正确的对象。
我还尝试使用更标准的方式:
findOneAndUpdate({ _id: req.param.id }, {$addToSet: {.....}}).exec(...)
但是那样我实际上不知道如何从数组中获取具有特定键的对象,然后更新该对象的一部分。
我正在考虑的其他 2 个选项:
由于您并没有真正使用 findOneAndUpdate (因为您没有提供实际更新),您可以简单地使用findOne
并尝试以下操作:
exports.vote = (req, res) => {
News.findOne({ _id: req.params.id }).exec(err, tempItem) => {
let option = tempItem.poll.options.find(({optionName}) => optionName == req.body.optionName)
option.optionVotes.push(req.user._id)
console.log(option)
tempItem.save(err => {
if (!err) {
return res.status(200).send()
}
})
}
}
那将是一种方法。我认为最好的方法是利用该update
部分并findOneAndUpdate
与传入的更新对象一起使用。
像这样:
findOneAndUpdate({
_id: req.param.id, 'poll.options.optionName': req.body.optionName
},
{ $addToSet:
{ 'poll.options.$.optionVotes': req.user._id }
}).exec(...)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句