Search code examples
node.jsmongodbexpressmonk

Mongodb authentication with nodejs and Monk


I keep getting an error when attempting to query a collection on a mongodb that I have (appeared to) successfully connect to in my app.js file.

var mongo = require('mongodb');
var monk = require('monk');
var db = monk('mongodb://USERNAME:PASSWORD@localhost:27017/test_db');

var app = express();

// Make our db accessible to our router
app.use(function(req,res,next){
        req.db = db;
        next();
});

It connects and then in my router file:

/* users.js*/

router.post('/login', function(req, res, next) {

   var params = req.body;
   var userid = params.userid;
   var pw     = params.password
   var db = req.db;
   var userdb = db.get('users');
   userdb.findOne({'userid' : userid}, function(e,user) {
     if (e) {
       console.log("error reading user doc ->");
       console.log(e);
       return;
     } else {
       ....
     }
  });
});

I get the following error after querying the collection:

{ [MongoError: auth failed] name: 'MongoError', ok: 0, errmsg: 'auth failed', code: 18 }

Solution

  • Check out the MongoDB docs for options:

    http://mongodb.github.io/node-mongodb-native/2.1/reference/connecting/connection-settings/

    You'll notice that username and password are not valid options. If you are connecting to test_db and your root user is in another database (lets say admin) you should use authSource: admin. You connection string would look like this:

    var db = monk('user:pass@localhost:27017/test_db',{authSource:'admin'});
    

    This was confusing me when I was trying to connect to to my database but my auth user was in another.

    Hope it helps someone!