使用NodeJS在MongoDB中更新数组中的单个元素,而无需知道索引

时间:2018-12-12 18:02:13

标签: node.js database mongodb

在我的数据库中,我看起来像这样:

 "_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")

}

但是,似乎在更新查询中不允许使用加号: enter image description here (无视console.log(theString),theString不存在,我知道,但这不是问题。)

因此,我尝试进行此查询

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: (....)

有人可以帮助我如何正确地从客户端接收的索引进行更新吗?

1 个答案:

答案 0 :(得分:1)

数组索引可通过括号表示法访问。

await User.update(
  {_id: req.session.userId},
  {$set: { notificationMessages[arrayIndex].showNotification: false }}
)

尝试不使用单引号。如果它不起作用,您也可以尝试像下面这样对字符串进行模板化:

await User.update(
  {_id: req.session.userId},
  {$set: { `notificationMessages[${arrayIndex}].showNotification`: false }}
)