3

When I query right after creating and opening mongoose connection as shown below, the query callback is hit and docs 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 the connection in an initDB function and make the query later on as shown below, the callback is not called. initDB is being called before express server is started.

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!

1 Answer 1

1

This is most probably because the callback passed to db.once('open', ... is being called only once when a connection to your database has been established. Try moving the call to db.once() into your initDB() function as follows:

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);
  });
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.