2-line NodeJS application crashes on mongoose.conn

2019-09-20 03:00发布

问题:

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.