'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



Solution 1:[1]

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!

Solution 2:[2]

i think you forget to define the env variable or maybe you forget to call config method of dotenv packages on server or starter file config it

const dotenv = require("dotenv")
dotenv.config()

on your watched file or starter... then use process.env.VARIABLE or for testing you mongo connection use simple string url like that :

mongodb://localhost:27017/database_name

Solution 3:[3]

adding directConnection=true to connection string worked for me

mongoose.connect("MONGO_URI=mongodb://localhost:27017/test-db?directConnection=true
"); 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mlamp
Solution 2 reza babakhani
Solution 3 Javed