Victor Ferreira
Victor Ferreira

Reputation: 6449

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

Upvotes: 0

Views: 3102

Answers (1)

Siddharth Yadav
Siddharth Yadav

Reputation: 393

  1. Log into the mongo shell via terminal
user@ubuntu:~$ mongo

and switch to admin DB

> use admin
  1. Create a user with the "userAdminAnyDatabase" role, which grants the privilege to create other users on any existing database.
> db.createUser(
  {
    user: "adminUser",
    pwd: "adminPwd",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)
  1. Disconnect from the mongo shell
  2. You need to enable authentication in mongod configuration file. Open /etc/mongod.conf or /etc/mongodb.conf
security:
    authorization: "disabled"

change it to

security:
    authorization: "enabled"
  1. Restart mongodb service
user@ubuntu:~$ sudo service mongodb restart

or

user@ubuntu:~$ sudo service mongod restart
  1. Connect and authenticate as the user administrator
user@ubuntu:~$ mongo admin
> db.auth("adminUser", "adminPwd")
1
  1. Create additional users as needed
> use myAmazingApp
> db.createUser(
  {
    user: "userApp",
    pwd: "passwordApp",
    roles: [ { role: "readWrite", db: "myAmazingApp" } ]
  }
)
  1. While connecting mongoose you can pass it in the connection URI or as options
mongoose.connect('mongodb://userApp:passwordApp@localhost:27017/myAmazingApp');

or

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

Upvotes: 2

Related Questions