且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用猫鼬更新多个文档失败

更新时间:2023-11-09 22:07:22

我已经设置了按预期工作的小例子,首先我调用 start() 来创建一些用户,然后 update()

var mongoose = require('mongoose');//v4.2.7var userSchema = mongoose.Schema({删除:数字,名称:字符串});var User = mongoose.model('user', userSchema);mongoose.connect('mongodb://127.0.0.1:27017/user');//开始();函数开始(){for (var i = 0; i  ', 用户);};User.find({}, function(err, docs){console.log('找到 ---> ', err, docs);});}更新();函数更新(){User.update({deleted:1}, {$set: {deleted: 0}}, {multi:true}, function(err, numAffected){console.log('更新 ---> ', err, numAffected);});}

我不确定为什么更新不适用于 where(...)

函数更新(){//这不起作用User.where({deleted:1}).update({$set: {deleted: 0}}, {multi:true}, function(err, numAffected){console.log('更新 ---> ', err, numAffected);});}

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.

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);
    });
}