Mongoose.js instance.save() 回调未触发 [英] Mongoose.js instance.save() callback not firing
问题描述
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')
}});
错误"或无错误"都不会打印到终端.更重要的是 connection.on '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.
推荐答案
在这种情况下,您将模型添加到全局 mongoose 对象,但打开了一个单独的连接 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.
这可以通过在全局 mongoose 连接上连接到 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屋!