node.js - How to create new User with password on MongoDB and connect from NodeJS application
问题描述
I need some help with setting up my NodeJS application to connect with the MongoDB with credentials.
I'm confused with creating user on the admin
database, or on the database I will store my documents, and then connecting to it from my application.
So, let's say I have this MongoDB service running on localhost
port 27017
and my database is called myAmazingApp
. I want to create a user with Read/Write permissions on this now empty database and set user userApp
and password passwordApp
.
I'm using Mongoose
on NodeJS.
My question includes where and how I must create this User/Role/whatever on MongoDB.
By the way, right now this is my connection string
mongodb://userApp:passwordApp@localhost:27017/myAmazingApp
and I am connecting with mongoose.connect
.
It gives me Authentication failed
解决方案
- 通过终端登录 mongo shell
user@ubuntu:~$ mongo
并切换到管理数据库
> use admin
- 创建一个具有“userAdminAnyDatabase”角色的用户,该角色授予在任何现有数据库上创建其他用户的权限。
> db.createUser(
{
user: "adminUser",
pwd: "adminPwd",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
- 断开与 mongo shell 的连接
- 您需要在 mongod 配置文件中启用身份验证。打开 /etc/mongod.conf 或 /etc/mongodb.conf
security:
authorization: "disabled"
将其更改为
security:
authorization: "enabled"
- 重启mongodb服务
user@ubuntu:~$ sudo service mongodb restart
或者
user@ubuntu:~$ sudo service mongod restart
- 以用户管理员身份连接和验证
user@ubuntu:~$ mongo admin
> db.auth("adminUser", "adminPwd")
1
- 根据需要创建其他用户
> use myAmazingApp
> db.createUser(
{
user: "userApp",
pwd: "passwordApp",
roles: [ { role: "readWrite", db: "myAmazingApp" } ]
}
)
- 连接 mongoose 时,您可以在连接 URI 中或作为选项传递它
mongoose.connect('mongodb://userApp:passwordApp@localhost:27017/myAmazingApp');
或者
mongoose.connect('mongodb://localhost:27017/myAmazingApp', {useNewUrlParser: true, user: "userApp", pass: "user:passwordApp"});
推荐阅读
- javascript - 如何使用 Mocha 和 Chai 证明函数的返回对象是作为参数提供给函数的参数的“克隆”?
- c# - 如何修复 (CS0019) 运算符“!=”不能应用于“随机”和“整数”类型的操作数
- graphql - 基于 GraphQL 查询上的另一个字段跳过字段
- julia - 是否可以在 Julia 中重塑稀疏数组?
- sql - 使用窗口函数?
- python - 我希望我的播放器(图像)左右移动
- sql-server - 在报告存储过程中可视化数据流
- java - Cassandra 触发器无法从 Set<> 类型中获取值
- javascript - 在 Python 中解析 JS
- c - 为什么GCC首先将整数加载到eax,然后再加载到其他一些相关寄存器?