Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs Mongoose Error: getaddrinfo ENOTFOUND undefined undefined:27017

I'm trying to switch to mongoose from using just the native mongodb and having some trouble.

Connecting to the db as I did previously works fine:

var db;

var passDb = function(req, res, next) {
    if (!db) {
        mongo.connect(process.env.MONGOLAB_URI, function(err, database) {
            if (err) throw err;
            db = database;

            req.db = db;
          next();
        });
    } else {
      req.db = db;
      next();
    }
}

But the way I'm trying to do it now throws an error:

var mongoose     = require('mongoose');

var Poll         = require('./app/models/poll');

mongoose.connect(process.env.MONGOLAB_URI);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
});

The error:

connection error: { [MongoError: getaddrinfo ENOTFOUND undefined undefined:27017
]
  name: 'MongoError',
  message: 'getaddrinfo ENOTFOUND undefined undefined:27017' }

Any ideas what is causing this?

edit: it works when I use the database uri directly, but not when I use the environment variable. I have checked and triple checked that everything is typed correctly, it refuses to use the environment variable and I have to put it directly in the code :S

like image 867
mlamp Avatar asked Jan 07 '23 11:01

mlamp


2 Answers

Ok, I figured out my mistake, I was connecting to the database before calling require('dotenv').load();. Mystery solved!

mongoose.connect(process.env.MONGOLAB_URI); now works!

like image 74
mlamp Avatar answered Feb 07 '23 19:02

mlamp


adding directConnection=true to connection string worked for me

mongoose.connect("MONGO_URI=mongodb://localhost:27017/test-db?directConnection=true
"); 
like image 20
javed Avatar answered Feb 07 '23 17:02

javed