问题描述
我有一些数据库,不想为每个数据库创建单独的用户帐户. MongoDB支持使用另一个数据库中定义的帐户对访问数据库进行身份验证的概念,但是语法示例很难找到.
I have a few databases and didn't want to create separate user accounts for each one. MongoDB supports the notion of authenticating access to a database using accounts defined in another database but examples of syntax are hard to come by.
当我终于弄清楚了这个问题时,我正要提出一个问题.如果它可以帮助别人
I was on the verge of posting a question when i finally figured it out. Here goes in case it helps someone else
推荐答案
以下是mongodb,mongoose,节点设置的语法.
Here's the syntax for a mongodb, mongoose, node setup.
-
通过mongo shell在admin数据库中创建数据库用户
Create the database user in the admin database from the mongo shell
use admin
db.addUser( { user: "mydbuser", pwd: "mypassword", roles: [ ] } )
创建数据库并添加用户-userSource指示凭据在管理数据库中定义
Create the database and add the user - the userSource indicates thatthe credentials are defined in the admin database
use mydb
db.addUser( { user: "mydbuser", userSource: "admin" , roles: [ "readWrite" , "dbAdmin"] } )
在猫鼬连接字符串中指定auth参数
Specify the auth parameter in the mongoose connection string
var myDB = mongoose.createConnection("mongodb://mydbuser:mypassword@myipaddress:27017/mydb" ,{auth:{authdb:"admin"}});
选项{auth:...}指定必须根据管理数据库对用户帐户进行身份验证.
the option {auth:...} is what specifies that the user account must be authenticated against the admin db.
类似地从mongo shell连接到数据库
Similarly to connect to the database from the mongo shell
mongo myipaddr:27017/mydb -u "mydbuser" -p "mypassword"
注意:用户"mydbuser"仅具有对mydb的读/写和管理员访问权限.您可以在此处中找到有关用户权限的更多信息.该场景的完整示例是此处
Note: The user "mydbuser" had only read/write and admin access to mydb. you can find more information on user privileges here. A fuller example of the scenario is here
这篇关于MongoDB和猫鼬访问一个数据库,同时对另一个数据库进行身份验证(NodeJS,猫鼬)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!