node.js - 使用 NodeJS 在不知道索引的情况下更新 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")
}
但是,似乎在更新查询中不允许有加号:( 忽略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 }}
)
推荐阅读
- apache-spark - 如何在 linux 上读取 part-00000.deflate 文件
- python - python中的行逗号删除
- laravel - 为什么模型看不到第二个外键?
- javascript - Angular/CSS/Javascript 创建一个可以突破包含 div 限制的弹出窗口
- react-native - 警告:不能调用 setState(或 forceUpdate)
- android - 恢复 RecyclerView 滚动位置
- python-2.7 - OSMnx 在基本使用中给出“TypeError: query must be a string or a list of query strings”
- wordpress - 如何将域从 http 重定向到 https
- php - Laravel:迁移文件是否只在迁移和回滚之间运行一次?
- r - 是否可以将代码和绘图(从所述代码)导出为 r 中的 pdf?