0

I try to update multiple documents with mongoose (3.8.37), but no document is updated.

I've done all things, that I've learned from other questions (see below):

  • Use a callback function
  • Specify multi:true

My update statement:

 Animal.where({ type: type}).update({deleted:1}, { multi: true, overwrite: true }, function (err,doc) { console.log("updates: "+doc); }); 

updates: 0

When I just count the documents, I'll get a result. => The query is correct

 Animal.where({type: type}).count(function (err,doc) { console.log("count: "+doc); }); 

count: 299

When I omit the multi:true option, the first record is updated. => The update statement is correct, too

 Animal.where({ type: type}).update({deleted:-1}, function (err,doc) { console.log("updates: "+doc); }); 

updates: 1

So where's the error?

There are several questions dealing with this topic. Unfortunately none of these solves my problem.

** UPDATE

I've added a log callback and discovered that no query to the mongodb is executed as long as the options (multi:true) are specified.

2
  • Try to change your .update({deleted:1},... to .update({ $set: { deleted:1}},{multi: true}, function... Commented Nov 23, 2015 at 18:39
  • @Molda Thanks for the tip. But I've already tried that. Didn't help. Commented Nov 23, 2015 at 19:18

1 Answer 1

1

I have setup small example which works as expected, first i called start() to create some users then update()

var mongoose = require('mongoose'); //v4.2.7 var userSchema = mongoose.Schema({ deleted: Number, name: String }); var User = mongoose.model('user', userSchema); mongoose.connect('mongodb://127.0.0.1:27017/user'); //start(); function start(){ for (var i = 0; i < 5; i++) { var user = new User({ deleted: 1, name: i }); user.save(); console.log('user ---> ', user); }; User.find({}, function(err, docs){ console.log('found ---> ', err, docs); }); } update(); function update (){ User.update({deleted:1}, {$set: {deleted: 0}}, {multi:true}, function(err, numAffected){ console.log('updated ---> ', err, numAffected); }); } 

I'm not sure why update doesn't work with where(...)

function update (){ // this doesn't work User.where({deleted:1}).update({$set: {deleted: 0}}, {multi:true}, function(err, numAffected){ console.log('updated ---> ', err, numAffected); }); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Great! Works: User.where().update() Doesn't work: User.where().update(multi:true) => Conclusion: Always use User.update() as Molda suggests!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.