首页 > 解决方案 > 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

标签: node.jsmongodbmongoosenosql

解决方案


  1. 通过终端登录 mongo shell
user@ubuntu:~$ mongo

并切换到管理数据库

> use admin
  1. 创建一个具有“userAdminAnyDatabase”角色的用户,该角色授予在任何现有数据库上创建其他用户的权限。
> db.createUser(
  {
    user: "adminUser",
    pwd: "adminPwd",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)
  1. 断开与 mongo shell 的连接
  2. 您需要在 mongod 配置文件中启用身份验证。打开 /etc/mongod.conf 或 /etc/mongodb.conf
security:
    authorization: "disabled"

将其更改为

security:
    authorization: "enabled"
  1. 重启mongodb服务
user@ubuntu:~$ sudo service mongodb restart

或者

user@ubuntu:~$ sudo service mongod restart
  1. 以用户管理员身份连接和验证
user@ubuntu:~$ mongo admin
> db.auth("adminUser", "adminPwd")
1
  1. 根据需要创建其他用户
> use myAmazingApp
> db.createUser(
  {
    user: "userApp",
    pwd: "passwordApp",
    roles: [ { role: "readWrite", db: "myAmazingApp" } ]
  }
)
  1. 连接 mongoose 时,您可以在连接 URI 中或作为选项传递它
mongoose.connect('mongodb://userApp:passwordApp@localhost:27017/myAmazingApp');

或者

mongoose.connect('mongodb://localhost:27017/myAmazingApp', {useNewUrlParser: true, user: "userApp", pass: "user:passwordApp"});

推荐阅读