天天看点

mongodb设置用户名和密码并用node连接

我用的mongo的版本是4.0.4

1、设置用户名和密码

1.1 设置admin库的用户名密码

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
xxxx  0.000GB
> use admin
switched to db admin
> db.createUser({ user: "admin", pwd: "admin", roles: [{ role: "userAdminAnyDatabase", db: "admin" }] })
Successfully added user: {
        "user" : "admin",
        "roles" : [
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ]
}
> db.auth("admin","admin")
1
           

1.2 重启mongo带上验证

因为我是源码安装的mongo,没有mongod.conf文件,所以直接命令行加上验证参数了,就是–auth,如下所示:

./mongod --bind_ip=0.0.0.0 --port=27017 --fork --logpath=/data/logs/mongolog.log --auth
           

1.3 建立xxxx库的用户名密码

用admin账户登录admin数据库,验证通过后建立别的数据库的用户。

[[email protected] bin]# ./mongo
MongoDB shell version v4.0.4
connecting to: mongodb://127.0.0.1:27017
Implicit session: session { "id" : UUID("92616552-2489-4363-9b11-da4b69b4a167") }
MongoDB server version: 4.0.4
> use admin
switched to db admin
> db.auth("admin","admin")
1
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
xxxx  0.000GB
> use xxxx
switched to db xxxx
> db.createUser({ user: "xxxxuser", pwd: "yyyy", roles: [{ role: "dbOwner", db: "xxxx" }] })
Successfully added user: {
        "user" : "xxxxuser",
        "roles" : [
                {
                        "role" : "dbOwner",
                        "db" : "xxxx"
                }
        ]
}
> db.auth("xxxxuser","yyyy")
1
>
           

2. node连接

在网上找了好多都没找到,mongo官网的文档也不清楚,不过最终还是解决了:

"mongodb://xxxxuser:[email protected]:27017/?authSource=xxxx"
           

有一点要说的,就是authSource=xxxx和添加xxxxuser用户的时候设置的db应一致,不然连不上,惭愧。。。

参考文献:

https://blog.csdn.net/fofabu2/article/details/78983741