Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback function never called after Mongoose query is executed

The following is my code:

mongoose.connect('mongodb://localhost/mydatabase');
  var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  console.log('DB connection opened');
});
// ...
var dbCallback = function(err, body) {
  // ...
};
// ...
var StuffModel = mongoose.model('Stuff', StuffSchema);
StuffModel.find({}).exec(dbCallback);

The dbCallback function is never called. Any help would be greatly appreciated!

like image 945
Branka Avatar asked Feb 19 '14 22:02

Branka


People also ask

What is callback in mongoose?

A mongoose query can be executed in one of two ways. First, if you pass in a callback function, Mongoose will execute the query asynchronously and pass the results to the callback . A query also has a . then() function, and thus can be used as a promise.

Does mongoose query return a promise?

Mongoose queries are not promises. They have a . then() function for co and async/await as a convenience.

What does findOne return mongoose?

Mongoose | findOne() Function The findOne() function is used to find one document according to the condition. If multiple documents match the condition, then it returns the first document satisfying the condition.

What is select in mongoose?

select() is a method of Mongoose that is used to select document fields that are to be returned in the query result. It is used to include or exclude document fields that are returned from a Mongoose query. The select() method performs what is called query projection.


2 Answers

Have you tried doing your query after the database connection opens? I don't have a Mongoose server to test it, but that would be my first guess.

var Stuff = mongoose.model('Stuff', StuffSchema);

db.once('open', function () {
  Stuff.find({}, function (e, body) {
    console.log('It worked!');
  });
});

Sorry, if this doesn't end up fixing it.

like image 75
aleclarson Avatar answered Oct 18 '22 04:10

aleclarson


Make sure that you are actually connected to your Mongo instance, otherwise queries will be left hanging and often no error is thrown or returned. An error in my Mongo URI was causing this for me.

In your code, you have your Mongo URI set to mongodb://localhost/mydatabase. I imagine that this is probably not correct and is the cause of your problem. Change your URI to just localhost:27017, which is the default port that Mongo is set to run on.

like image 33
S. Heutmaker Avatar answered Oct 18 '22 04:10

S. Heutmaker