node.js - 在不知道索引的情况下使用 NodeJS 更新 MongoDB 中数组中的单个元素

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

任何人都可以帮助我如何正确更新从客户端收到的索引?

最佳答案

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

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

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

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

关于node.js - 在不知道索引的情况下使用 NodeJS 更新 MongoDB 中数组中的单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53748851/

相关文章:

javascript - Firebase .orderByChild().equalTo().once().then() 当 child 不存在时 promise

mongodb - 集成 Google App Engine 和 Compute MongoDB,可能吗?

javascript - 无法从模板获取数据并将其传递给 Controller ​​ Angularjs

javascript - Node Angular View 错误

javascript - 如果用户在出站调用中未接听,Twilio 会发送语音消息

mysql - 如何在 Sequelize 中实现聚类?

database - 在 Sybase IQ 中设置用户的默认数据库/模式

database - 使用一个复杂的查询还是使用几个更简单的查询更好?

mysql - swingbench 数据生成器连接字符串

javascript - 从 MongoDB 中的嵌套数组中查找公共(public)属性