我创建了具有完整凭据的MongoDB用户,但尝试使用猫鼬连接到数据库时身份验证失败

时间:2019-03-24 19:50:42

标签: node.js mongodb mongoose

我正在使用MongoDB服务器版本:4.0.6和Mongoose版本5.4.18。我创建了以下MongoDB用户:

"_id" : "admin.matt",
"user" : "matt",
"db" : "admin",
"roles" : [
        {
                "role" : "readWrite",
                "db" : "user-data"
        },
        {
                "role" : "userAdminAnyDatabase",
                "db" : "admin"
        },
        {
                "role" : "readWrite",
                "db" : "admin"
        },
        {
                "role" : "dbAdminAnyDatabase",
                "db" : "admin"
        },
        {
                "role" : "readWriteAnyDatabase",
                "db" : "admin"
        }
],
"mechanisms" : [
        "SCRAM-SHA-1",
        "SCRAM-SHA-256"
]

我正在尝试使用以下猫鼬命令进行连接:

mongoose.connect('mongodb://matt:passwordexample!@localhost:27017/user-data', {useNewUrlParser: true});

它回复 MongoError:身份验证失败。

我尝试了多种连接格式,但没有任何效果。我的用户凭证设置不正确吗?谢谢。

这是我的package.json。如果我有猫鼬,我在这里需要MongoDB吗?

"dependencies": {
    "body-parser": "^1.18.3",
    "express": "^4.16.4",
    "express-handlebars": "^3.0.2",
    "express-session": "^1.15.6",
    "express-validator": "^5.3.1",
    "forever": "^0.15.3",
    "mongoose": "^5.4.18",
    "nodemon": "^1.18.10",
    "path": "^0.12.7"
  },

2 个答案:

答案 0 :(得分:0)

如果用户名或密码包含@符号,冒号:,斜杠/或百分号%字符,请使用百分号编码。

https://docs.mongodb.com/manual/reference/connection-string/#urioption.authSource

或者您可以尝试一下

db.createUser(
  {
    user: "matt",
    pwd: "passwordexample!",
    roles: [ { role: "root", db: "admin" } ]
  }
)

答案 1 :(得分:0)

您未在连接字符串中指定authSource: mongodb://matt:passwordexample!@localhost:27017/user-data?authSource=admin