Mongoose gives error while connecting using mongolab uri ?

582 views Asked by At

It gives the following error-

mongoose connection error:  { [MongoError: connect EINVAL] name: 'MongoError', message: 'connect EINVAL' }

/home/user/Documents/oes/node_modules/connect-mongo/node_modules/mongodb/lib/server.js:228
    process.nextTick(function() { throw err; })
                                        ^
Error: connect EINVAL
at errnoException (net.js:905:11)
at connect (net.js:767:19)
at net.js:846:9
at asyncCallback (dns.js:68:16)
at Object.onanswer [as oncomplete] (dns.js:121:9)

14 Jun 18:04:11 - [nodemon] app crashed - waiting for file changes before starting...

1

There are 1 answers

1
Bikash On

This is a very old problem, But as no one has yet answered it.

We often see that users have problems connecting to MongoLab using the Mongoose driver. The root cause is almost always incorrect configuration of the driver, particularly around timeouts. The following is a connection example using the MongoLab-recommended driver options:

// mongoose 4.3.x
var mongoose = require('mongoose');



/* 
 * Mongoose by default sets the auto_reconnect option to true.
 * We recommend setting socket options at both the server and replica set level.
 * We recommend a 30 second connection timeout because it allows for 
 * plenty of time in most operating environments.
 */
var options = { server: { socketOptions: { keepAlive: 300000, connectTimeoutMS: 30000 } }, 
                replset: { socketOptions: { keepAlive: 300000, connectTimeoutMS : 30000 } } };       

var mongodbUri = 'mongodb://user:pass@host:port/db';

mongoose.connect(mongodbUri, options);
var conn = mongoose.connection;             

conn.on('error', console.error.bind(console, 'connection error:'));  

conn.once('open', function() {
  // Wait for the database connection to establish, then start the app.                         
});

If this doesn't help, please ensure your password or username doesn't has any special character, Try to connect it via CMD first.

Hope I helped :)