在NodeJS中更新多个MongoDB文档似乎不起作用 [英] Updating more than one MongoDB document in NodeJS doesn't seem to work

查看:114
本文介绍了在NodeJS中更新多个MongoDB文档似乎不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I know this question has been asked many times but I've looked it up for over 30 minutes and I honestly can't find what I'm doing wrong.

我想更新我的mongo数据

I want to update my mongo data

这是两个文档的示例

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

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

我想将用户名更改为其他名称.

I want to change to usernames to something else.

例如,约翰·塞纳(JOHN CENA).

For example to JOHN CENA.

这是我正在使用的代码.

Here is the code I'm using.

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

updateUsers()

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

但是它不起作用,甚至没有更改单个文档. 我还发现有些人用过

But it doesn't work, not even a single document is changed. I've also found that some people used

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

但是那给了我一个错误,所以我想这是旧版本的代码.

But that one gives me an error, so I guess it's code from an older version.

但是,如果我使用

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

(这显然会永远循环,因为它自称为循环).最后,每个文档都将使用JOHN CENA用户名进行更新.

(Which obviously loops forever since it calls itself). Every single document ends up being updated with the JOHN CENA user name.

我不明白这里发生了什么,有人可以帮我吗?

I don't understand what's going on here, can anybody help me please ?

在下面的注释中,用户建议添加一个空的回调.我做了,现在可以正常使用了.我非常感谢他(@Sergio Tulentsev),希望该主题对将来有所帮助.

EDIT : In the comments below a user suggested adding an empty callback. Which I did and now it works as intended. My thanks go to him (@Sergio Tulentsev) and I hope this thread will help somebody else in the future.

推荐答案

文档在

As noted in the docs for update, if you don't want to provide a callback, you need to call exec on the returned Query to execute it:

要更新文档而无需等待MongoDB的响应,请执行 不传递回调,然后在返回的查询上调用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调用,或者提供回调:

So either chain an exec call on your update or provide a callback:

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

OR

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

这篇关于在NodeJS中更新多个MongoDB文档似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆