Mongoose.js instance.save()回调未触发 [英] Mongoose.js instance.save() callback not firing

查看:83
本文介绍了Mongoose.js instance.save()回调未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var mongo = require('mongoose');
var connection = mongo.createConnection('mongodb://127.0.0.1/test');

connection.on("error", function(errorObject){
  console.log(errorObject); 
  console.log('ONERROR');
});

var Schema = mongo.Schema;
var BookSchema = new Schema({ title : {type : String, index : {unique : true}}});
var BookModel = mongo.model('abook', BookSchema);
var b = new BookModel({title : 'aaaaaa'});

b.save( function(e){ 
  if(e){
    console.log('error')
  }else{
    console.log('no error')
}});

错误"或无错误"均未打印到终端.更重要的是,关于``错误''的连接似乎也不会触发.我已经确认MongoDb正在运行.

Neither the 'error', or 'no error' are printed to the terminal. What's more the connection.on 'error' doesn't seem to fire either. I have confirmed that MongoDb is running.

推荐答案

在这种情况下,您要将模型添加到全局猫鼬对象中,但打开一个单独的不属于模型的连接mongo.createConnection().由于模型没有连接,因此无法保存到数据库.

this is a case where you are adding the model to the global mongoose object but opening a separate connection mongo.createConnection() that the models are not part of. Since the model has no connection it cannot save to the db.

这可以通过在全局猫鼬连接上连接到mongo来解决:

this is solved either by connecting to mongo on the global mongoose connection:

var connection = mongo.createConnection('mongodb://127.0.0.1/test');
// becomes
var connection = mongo.connect('mongodb://127.0.0.1/test');

或通过将模型添加到单独的连接中:

or by adding your models to your separate connection:

var BookModel = mongo.model('abook', BookSchema);
// becomes
var BookModel = connection.model('abook', BookSchema);

这篇关于Mongoose.js instance.save()回调未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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