这个问题已经有了答案:
using a variable in mongodb update
1个答案
在我的数据库中,我有这样的东西:
"_id" : ObjectId("5c0d9d54df58cb2fdc7f735a"),
"notificationMessages" : [
{
"message" : "Some message 1",
"showNotification" : true,
"projectId" : "5c0e40683500fe72a8e3ce8f"
},
{
"message" : "Some message 2",
"showNotification" : true,
"projectId" : "5c0e6e113500fe72a8e3ce90"
}
],
我想更新“shownotification”为false,当点击我客户端的具体消息时。为此,我将单击的数组的索引从客户端发送到nodejs服务器,并尝试将该结果用作更新查询的索引,但它不起作用。首先我试着这样做:
exports.delete_notification = async function(req,res) {
let arrayIndex = req.body.index;
console.log("This is the arrayIndex")
console.log(arrayIndex)
await User.update(
{_id: req.session.userId},
{$set: {'notificationMessages.' + arrayIndex + '.showNotification': false }}
)
res.status(200).json("done")
}
但是,似乎在更新查询中不允许使用tho plus:
(忽略控制台。日志(字符串),字符串不存在,我知道,但这不是问题。)
所以我试着做了这个查询
await User.update(
{_id: req.session.userId},
{$set: {'notificationMessages.arrayIndex.showNotification': false }}
)
但这会导致以下错误:
(node:20656) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: Cannot create field 'arrayIndex' in element {notificationMessages: [ { message: (....)
有谁能帮助我正确更新从客户端收到的索引吗?
最佳答案
数组索引可以通过括号符号访问。
await User.update(
{_id: req.session.userId},
{$set: { notificationMessages[arrayIndex].showNotification: false }}
)
试着不引用一个引号。如果不起作用,您也可以尝试将字符串模板化,如下所示:
await User.update(
{_id: req.session.userId},
{$set: { `notificationMessages[${arrayIndex}].showNotification`: false }}
)