最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Callback function never called after Mongoose query is executed - Stack Overflow

programmeradmin2浏览0评论

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!

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!

Share Improve this question edited Feb 11, 2015 at 12:10 laggingreflex 34.6k36 gold badges143 silver badges200 bronze badges asked Feb 19, 2014 at 22:32 BrankaBranka 4791 gold badge5 silver badges12 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 12

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.

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.

I faced similar issue.

I was calling process.exit(0) after queries, so the app exited before mongoose have a chance to run callback.

So i removed process.exit(0) and it worked!

发布评论

评论列表(0)

  1. 暂无评论