gpt4 book ai didi

node.js - 在 NodeJS 中更新多个 MongoDB 文档似乎不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 23:35:30 25 4
gpt4 key购买 nike

所以我知道这个问题已经被问过很多次了,但我已经查了 30 多分钟了,老实说我找不到我做错了什么。

我想更新我的 mongo 数据

这是两个文档的示例

{
"_id" : ObjectId("561e34c68b7639481c38ce62"),
"id" : "1657999143",
"timeTakenAt" : 1444820166833.0000000000000000,
"userName" : "a",
"__v" : 0
}

{
"_id" : ObjectId("561e34c68b7639481c38ce63"),
"id" : "1659143",
"timeTakenAt" : 1444820166833.0000000000000000,
"userName" : "b",
"__v" : 0
}

我想将用户名更改为其他内容。

例如约翰·塞纳。

这是我正在使用的代码。

...
var UserModel = mongoose.model('userSchema', userSchema);
...

updateUsers()

function updateUsers(){
UserModel.update({}, {$set: {userName: 'JOHN CENA'}}, {multi:true})
}

但是不起作用,连一个文档都没有改变。我还发现有些人使用

UserModel.update({}, {$set: {userName: 'JOHN CENA'}}, false,true)

但是那个给了我一个错误,所以我猜它是来自旧版本的代码。

但是,如果我使用

UserModel.update({}, {$set: {userName: 'JOHN CENA'}},  {multi:true}, updateUsers)

(这显然会永远循环,因为它调用自身)。每个文档最终都会使用 JOHN CENA 用户名进行更新。

我不明白这是怎么回事,有人可以帮助我吗?

编辑:在下面的评论中,用户建议添加一个空回调。我做到了,现在它按预期工作了。我要感谢他 (@Sergio Tulentsev),我希望这篇文章将来能对其他人有所帮助。

最佳答案

update 的文档中所述,如果您不想提供回调,则需要在返回的 Query 上调用 exec 来执行它:

To update documents without waiting for a response from MongoDB, do not pass a callback, then call exec on the returned Query

因此,要么在 update 上链接 exec 调用,要么提供回调:

function updateUsers(){
UserModel.update({}, {$set: {userName: 'JOHN CENA'}}, {multi:true}).exec();
}

或者

function updateUsers(){
UserModel.update({}, {$set: {userName: 'JOHN CENA'}}, {multi:true},
function(err, numAffected) {...});
}

关于node.js - 在 NodeJS 中更新多个 MongoDB 文档似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33123977/

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