问题
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?
回答1:
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.
回答2:
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.
回答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.
来源:https://stackoverflow.com/questions/26381660/auth-failed-error-when-specifying-database