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

问题描述 投票:0回答:2

我使用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命令进行连接:

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"
  },
node.js mongodb mongoose
2个回答
0
投票

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

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

或者你可以尝试这个,

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

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.