5

I'm trying to connect to a mongodb from my web application. However, I get an auth failed error from mongo when I specify the database I want to connect to. If I do not specify the db, then to connection is successful.

I have checked the spelling and if the database exits with the mongo command line show dbs

var dbURI = 'mongodb://root:pwd@localhost:27017/dbname';
mongoose.connect(dbURI, function(err) {
    if (err) throw err;
});

C:\Users\David\Documents\Bitbucket\productWebsite\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\base.js:245
        throw message;
              ^
MongoError: auth failed
    at Object.toError (C:\Users\David\Documents\Bitbucket\productWebsite\node_modules\mongoose\node_modules\mongodb\lib\mongodb\utils.js:114:11)
    at C:\Users\David\Documents\Bitbucket\productWebsite\node_modules\mongoose\node_modules\mongodb\lib\mongodb\db.js:1130:31
    at C:\Users\David\Documents\Bitbucket\productWebsite\node_modules\mongoose\node_modules\mongodb\lib\mongodb\db.js:1847:9
    at Server.Base._callHandler (C:\Users\David\Documents\Bitbucket\productWebsite\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\base.js:445:41)
    at C:\Users\David\Documents\Bitbucket\productWebsite\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\server.js:478:18
    at MongoReply.parseBody (C:\Users\David\Documents\Bitbucket\productWebsite\node_modules\mongoose\node_modules\mongodb\lib\mongodb\responses\mongo_reply.js:68:5)
    at null.<anonymous> (C:\Users\David\Documents\Bitbucket\productWebsite\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\server.js:436:20)
    at emit (events.js:95:17)
    at null.<anonymous> (C:\Users\David\Documents\Bitbucket\productWebsite\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\connection_pool.js:201:13)
    at emit (events.js:98:17)

I'm using Bitnami Mean stack for Windows

Can someone tell me what I am forgetting?

David
  • 965
  • 3
  • 12
  • 24

3 Answers3

14

It matters which database you try to authenticate to. Authenticate to the database where the user was created. You can switch to using other databases once authenticated.

wdberkeley
  • 11,531
  • 1
  • 28
  • 23
5

You might want to do something like this...

var opt = {
        user: config.username,
        pass: config.password,
        auth: {
            authdb: 'admin'
        }
    };

var connection = mongoose.createConnection(config.database.host, 'mydatabase', config.database.port, opt);

'authdb' option is the database you created the user under.

Leon
  • 5,701
  • 3
  • 38
  • 38
3

In my experience, I found that the reason might be the version difference between the mongoose and mongoDB. In my package.json the mongoose version is the 3.8.5 and my mongoDB version is 3.0.4, I changed the mongoose version 3.8.5 to 4.1.5 and ran the command:

npm update

and ran the app, that worked for me.

TommySM
  • 3,793
  • 3
  • 24
  • 36
Z.Dui.an
  • 31
  • 3