Reputation: 506
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.
I want to update my mongo data
Here's an example of two documents
{
"_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.
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.
However, if I use
UserModel.update({}, {$set: {userName: 'JOHN CENA'}}, {multi:true}, updateUsers)
(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 ?
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.
Upvotes: 1
Views: 160
Reputation: 311835
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:
To update documents without waiting for a response from MongoDB, do not pass a callback, then call
exec
on the returned Query
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) {...});
}
Upvotes: 2