猫鼬实例.save()无法正常工作 [英] Mongoose instance .save() not working

查看:77
本文介绍了猫鼬实例.save()无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Mongoose和MongoDb有问题

I have a problem with Mongoose and MongoDb

非常有趣的是,只有Model.update起作用,而save却不起作用,甚至不会触发回调.

It is very interesting that only Model.update works and save never works and does not even fire callback.

猫鼬:4.4.5 MongoDB:3.0.8

Mongoose: 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");
})

即使回调未触发.连接成功打开.它从不调用回调.

Even callback is not firing. Connection successfully opens. It never invokes callback.

  1. 尝试使用var User = connection.model('User', schema)无效.

推荐答案

我不会删除此问题,因为人们也可能会遇到此问题.实际上问题与MongoDb或Mongoose无关.致电Object.save()时,责任链如下:

I am not going to delete this question because people may encounter this problem too. Actually problem was not related with MongoDb or Mongoose. When you call Object.save() responsibility chain is like below:

  1. Schema.pre(保存")
  2. 将数据保存到dabe
  3. Schema.post(保存")
  1. Schema.pre("save")
  2. Save data to dabe
  3. Schema.post("save")

因此,如果您阻止pre("save")并且不调用next()处理程序,则将无法保存文档.这是我的情况,我忘记了if语句内的next()调用,并试图在3小时以上的时间内发现错误.

So if you block pre("save") and don't call next() handler you won't be able to save your document. This was my case, I forgot the next() call inside an if statement and tried to find the error for more than 3 hours.

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

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

When this.trial == true, next handler won't be reachable.

为防止出现此类错误,我们应该注意分支机构的覆盖范围,记者可以向我们展示未经测试的代码.您的问题也可能与此有关. 如果要保存文档,请确保您正在致电next().

To prevent errors like this we should take care of branch coverage, reporters can show us untested codes. Your problem might be related with this too. Be sure you are calling next() if your document should be saved.

固定版本

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

这篇关于猫鼬实例.save()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆