在另一个函数中创buildMongoose连接时,不会调用查询callback

当我查询创build并打开mongoose连接后,如下所示,查询callback命中,文档加载。

var db, mongoose = require('mongoose'); ... MyClass.prototype.query = function(model, criteria, callback) { var options = { server: { auto_reconnect: true, socketOptions : { keepAlive: 1 } } }; mongoose.connect('mongodb://localhost/mydatabase', options); db = mongoose.connection; db.on('error', console.error.bind(console, 'Error:')); db.once('open', function () { model.find(criteria).exec(function(err, docs) { callback(err, {}, docs); }); }); }; 

但是,当我在initDB函数中创build连接并稍后进行查询时,不会调用callback。 在启动express服务器之前调用initDB

 var db, mongoose = require('mongoose'); ... function initDB() { var options = { server: { auto_reconnect: true, socketOptions : { keepAlive: 1 } } }; mongoose.connect('mongodb://localhost/mydatabase', options); db = mongoose.connection; db.on('error', console.error.bind(console, 'Error:')); } ... MyClass.prototype.query = function(model, criteria, callback) { db.once('open', function () { model.find(criteria).exec(function(err, docs) { callback(err, {}, docs); }); }); }; 

我在这里错过了什么? 任何帮助将不胜感激!

这很可能是因为传递给db.once('open', ...的callbackdb.once('open', ...在与数据库的连接build立时只被调用一次,试着把调用db.once()移到你的initDB()function如下:

 var db, mongoose = require('mongoose'); ... function initDB() { var options = { server: { auto_reconnect: true, socketOptions : { keepAlive: 1 } } }; mongoose.connect('mongodb://localhost/mydatabase', options); db = mongoose.connection; db.once('open', function () { console.log('Connected to database!'); }); db.on('error', console.error.bind(console, 'Error:')); } ... MyClass.prototype.query = function(model, criteria, callback) { model.find(criteria).exec(function(err, docs) { callback(err, {}, docs); }); };