猫鼬实例 .save() 不工作

新手上路,请多包涵

我对 Mongoose 和 MongoDb 有疑问

非常有趣的是,只有 Model.update 有效,而 save 永远不会有效,甚至不会触发回调。

猫鼬:4.4.5 MongoDB:3.0.8

特快路线

var mongoose = require('mongoose');
mongoose.connect("mongodb://127.0.0.1:27017/db");
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(callback) {
    console.log("connection to db open")
});
var User = require("../models/user.js");

用户模型

var user = new Schema({
    uid: { type: Number, required: true, unique: true},
    hwid: { type: String, default:""},
    bol:{type:String,default:""}
});

更新端点

工作版本: Model.update()

 User.update({_id: id}, {
    uid: 5,
}, function(err, numberAffected, rawResponse) {
    console.log(err);
})

不工作的版本,我必须解决这个问题: Object.save()

 User.find({_id:id}, function(err,user){
    if(err){
         console.log(err);
    }
    if(!user){
         console.log("No user");
    }else{
        user.uid = 5;
        user.save(function(err,news){
            console.log("Tried to save...");
        });
    }
    console.log("At least worked");
})

甚至回调也没有触发。连接成功打开。它从不调用回调。


  1. 尝试使用 var User = connection.model('User', schema) 不起作用。

原文由 Ahmet Can Güven 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 653
2 个回答

我不会删除这个问题,因为人们也可能会遇到这个问题。实际上问题与 MongoDb 或 Mongoose 无关。当您调用 Object.save() 责任链如下:

  1. Schema.pre(“保存”)
  2. 将数据保存到 dabe
  3. Schema.post(“保存”)

因此,如果您阻止 pre("save") 并且不调用 next() 处理程序,您将无法保存您的文档。这是我的情况,我在 if 语句中忘记了 next() 调用并试图找到错误超过 3 小时。

 user.pre("save", function(next) {
    if(!this.trial){
        //do your job here
        next();
    }
}

this.trial == true 时,下一个处理程序将无法访问。

为了防止这样的错误,我们应该注意分支覆盖,记者可以向我们展示未经测试的代码。您的问题也可能与此有关。 如果您的文档应该被保存,请确保您正在调用 next()

固定版本

user.pre("save", function(next) {
    if(!this.trial){
        //do your job here
    }
    next();
}

原文由 Ahmet Can Güven 发布,翻译遵循 CC BY-SA 4.0 许可协议

我也有同样的问题。我的问题是关于更改 db 中的数组,然后当我尝试使用 .save() 时,它不明白我更改了任何东西,然后 .save() 不起作用。我只是在使用 .save() 之前使用 markModified() ,我的问题就解决了。

这是我有问题的代码:(不工作)

 club.members[index].name = new_name;
club.save();

这是我解决的代码:(工作)

 club.members[index].name = new_name;
club.markModified('members');
club.save();

请享用!

原文由 Abolfazl Miadian 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏