2-line NodeJS application crashes on mongoose.connect() while trying to connect to a mongolab MongoDB database

我的梦境 提交于 2019-12-13 08:41:27

问题


I have the following NodeJS code:

var mongoose = require('mongoose');
mongoose.connect('mongodb://dev:dev@ds031632.mongolab.com:31632/mongodev');

And upon running it with node server.js, it hangs up for a few seconds and throws the following:

C:\Users\dev\work\code\local\nodejsplayground\restwithmongo\nod
dules\mongoose\node_modules\mongodb\lib\server.js:228
        process.nextTick(function() { throw err; })
                                            ^
Error
    at Object.<anonymous> (C:\Users\dev\work\code\local\nodejsp
round\restwithmongo\node_modules\mongoose\node_modules\mongodb\node_modules\mong
core\lib\error.js:42:24)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (C:\Users\dev\work\code\local\nodejsp
round\restwithmongo\node_modules\mongoose\node_modules\mongodb\node_modules\mong
core\index.js:2:17)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)

I pinged the server by console via this:

ping ds031632.mongolab.com

I tried installing mongodb with the windows installer and it's still not working


回答1:


This error happens when there is an error connecting to mongodb without an error callback to be called. To fix this error (and get the actual error,) add a callback to the .connect method, or, bind to the error event.

mongoose.connect(config.mongodb, function (err) {
  if (err) {
    console.log(err);
  }
});

or

mongoose.connect(config.mongodb);

var db = mongoose.connection;

db.on('error', function (err) {
  console.log('mongodb connection error: %s', err);
  process.exit();
});
db.once('open', function () {
  console.log('Successfully connected to mongodb');
  app.emit('dbopen');
});

If you find that nothing happens and it just hangs, wait 30 or so seconds and it will timeout, which simply means mongoose couldn't connect to mongodb, which could be caused by a very large number of different things, mostly related to network/dns/firewall/server configuration.



来源:https://stackoverflow.com/questions/29926210/2-line-nodejs-application-crashes-on-mongoose-connect-while-trying-to-connect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!