進入mongodb開始設定
mongosh --port 27017
進入增加authentication的db
use mydb
建立用戶
db.createUser( { user: "username", pwd: "password", roles: [ { role: "dbAdmin", db: "mydb" } ] } )
修改權限
db.grantRolesToUser("username",["readWrite"])
修改config file
sudo nano /etc/mongod.conf
增加
security: authorization: enabled
重啟MongoDB
sudo service mongod restart
測試
mongosh --port 27017 -u "username" -p "password" --authenticationDatabase "mydb"