gpt4 book ai didi

javascript - 更新 mongodb 中的嵌套值

转载 作者:太空宇宙 更新时间:2023-11-04 01:47:43 24 4
gpt4 key购买 nike

根据下面的代码,我希望为 req.body.update 设置一个变量。我不知道如何实现这一点。当我将其设置为 queryz 时,没有任何反应。

我为此使用 Mongoose 。

app.put('/application/todoupdate/:id/:index', function(req, res, next) {
console.log('accessed put route');
let item = 0;
let queryz = "todos." + item + ".todoText";
console.log(queryz);
User.where({_id: req.params.id}).update({
$set: {
"todos.0.todoText": req.body.update
// queryz: req.body.update
}
}).then(
res.send(req.body.update)
)
});

我的数据库结构是:

{
"_id": {
"$oid": "77777777777"
},
"todos": [
{
"todoText": "req success",
"timestamp": "7777777777777"
},
{
"todoText": "something",
"timestamp": "7777777777777"
}
]
}

我发现这允许我访问较低的级别:

app.put('/application/todoupdate/:id/:timestamp', function(req, res, next) {
console.log('accessed put route');
User.where({_id: req.params.id, "todos.timestamp":
req.params.timestamp}).update({
$set: {
"todos.$.todoText": req.body.update
}
}).then(
res.send(req.body.update)
)
});

最佳答案

您需要使用positional更新嵌套对象数组的运算符

User.update(
{ _id: req.params.id },
{ "$set": { "todos.$.todoText": "hello" } }
)

如果你想更新数组中的所有对象,那么你可以使用 $[] positional operator

User.update(
{ _id: req.params.id },
{ "$set": { "todos.$[].todoText": "hello" } }
)

关于javascript - 更新 mongodb 中的嵌套值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50844733/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com