Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

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

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:Usersdevworkcodelocal
odejsplayground
estwithmongo
od
dulesmongoose
ode_modulesmongodblibserver.js:228
        process.nextTick(function() { throw err; })
                                            ^
Error
    at Object.<anonymous> (C:Usersdevworkcodelocal
odejsp
round
estwithmongo
ode_modulesmongoose
ode_modulesmongodb
ode_modulesmong
coreliberror.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:Usersdevworkcodelocal
odejsp
round
estwithmongo
ode_modulesmongoose
ode_modulesmongodb
ode_modulesmong
coreindex.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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...