我用的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