Call request not called when Mongoose connection is created in another function

When I request immediately after creating and opening a mongoose connection, as shown below, the request callback hits and documents are loaded.

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);
    });
  });
};

However, when I create a connection in a function initDBand make a request later, as shown below, the callback is not called. initDBcalled before the server starts express.

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);
    });
  });
};

What am I missing here? Any help would be greatly appreciated!

+3
source share
1 answer

, , , , db.once('open', ..., , . db.once() 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.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);
  });
};
+1