Authentication failed when specifying database
I am trying to connect to mongodb
from my web app. However, I get auth failed error
from mongo when I specify the database that I want to connect to. If I do not specify db, then the connection is successful.
I have checked the spelling and if the database exits from 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 am using Windows bitnam
Can anyone tell me what I am forgetting?
source to share
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' is the database where you created the user.
source to share
In my experience, I found that the reason might be a difference in version between mongoose and mongoDB. In my package.json version, the mongoose version is 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 launched the app which worked for me.
source to share