问题
I can connect to the DB through terminal, but getting this error using mongoose and gulp. mongoose/node_modules/mongodb/lib/mongodb/connection/base.js:246 MongoError: auth failed
My connection string is:
mongodb://usr:psw@localhost:27017/dbname
Any idea what it can be?
回答1:
I installed MEAN at https://bitnami.com/stack/mean for windows 7 When install I make password is 123456
Syntax make connect to mongodb with mongoose
mongoose.connect("mongodb://[usr]:[pwd]@localhost:[port]/[db]",{auth:{authdb:"admin"}});
If have no
{auth:{authdb:"admin"}}
You will get error message "MongoError: auth failed"
Example: mongo-test/app.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://root:123456@localhost/test',{auth:{authdb:"admin"}});
mongoose.set('debug', true); // turn on debug
回答2:
just add ?authSource=yourDB&w=1
to end of db url
mongoose.connect('mongodb://user:password@host/yourDB?authSource=yourDB&w=1')
this work for me . &w=1
is important
回答3:
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.
回答4:
mongoose.connect("mongodb://[host]/[db]", { auth:{
authdb: "admin",
user: [username],
password: [pw]
}}).then(function(db){
// do whatever you want
mongoose.connection.close() // close db
})
回答5:
Do you have a user set up for dbname? By default, no user is required to connect to the database unless you explicitly set one. If you haven't, you should just try to connect to mongodb://localhost:27017/dbname
and see if you still get an error.
回答6:
I have found the solution hier, looks like when you create an user from the mongo shell, it makes SCRAM-SHA-1 instead of MongoDB-CR. So the solution to create a new user with MongoDB-CR authentication.
MongoDB-CR Authentication failed
回答7:
just make sure that your database is created. and also if your user is not added in the admin database, then make sure to add it by putting db.createUser( ... {user:'admin',pwd:'admin',roles:['root']} ... )
回答8:
This worked for me for mongod --version = db version v3.6.13
mongoose.connect('mongodb://localhost/expressapi', {
auth: {
authdb: "admin",
user: "root",
password: "root",
}
});
来源:https://stackoverflow.com/questions/30105823/mongoerror-auth-failed-mongoose-connection-sting