Reputation: 14950
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):
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.
Upvotes: 0
Views: 546
Reputation: 5704
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);
});
}
Upvotes: 1