首页 > 数据库 >Golang 使用 MongoDB 报错

Golang 使用 MongoDB 报错

时间:2022-09-22 17:23:32浏览次数:54  
标签:admin MongoDB 数据库 db Golang 报错 user role zs

在使用 MongoDB 时,URI格式一般为:

连接URI

mongodb://用户名:密码@127.0.0.1:27017
// 等同于
mongodb://用户名:密码@127.0.0.1:27017/admin

如果不指定数据库名,默认使用 admin 进行授权验证,当你指定了一个数据库名称,比如:

mongodb://用户名:密码@127.0.0.1:27017/user

测试 admin 数据库中的 system.users 信息中 user 数据库又没有用户的话,当你在对数据库进行 CRUD 时就会出现 auth error

// 信息已使用驱动库为准,大概就是授权错误
auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-1": (AuthenticationFailed) Authentication failed.

为了解决这问题,我们需要为 user 添加一个用户 比如zs

use user // 这个就是 uri 中的数据库

db.createUser({"user":"zs","pwd":"zs123!","roles":[{"role":"userAdminAnyDatabase","db":"admin"}]})

这里需要注意下 roledb 的值。

use user
db.createUser({"user":"zs","pwd":"zs123!","roles":[{"role":"readWrite","db":"log"}]})

这个只能保证你能够链接数据库,zs 也只是对 log 这个数据库有可读可写的权限,如果此时你要对读取另一个 group 数据库中的数据,那么又会出现授权错误

err:  (Unauthorized) not authorized on center to execute command 

你可以这样:

use user
db.createUser({"user":"zs","pwd":"zs123!","roles":[{"role":"readWrite","db":"log"}, {"role":"readWrite","db":"group"}]})

标签:admin,MongoDB,数据库,db,Golang,报错,user,role,zs
From: https://www.cnblogs.com/4zjq/p/16720121.html

相关文章