Connecting to MongoDB with authentication

I have a database (use myDatabase) where I set a user (

db.createUser({user: "username", pwd: "password", roles: ["readWrite","dbAdmin"]})

I want authentication when “use myDatabase” command is used.
Also in app js:

mongoose.connect('mongodb://localhost:27017/myDatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true

This connects to db too without username and password.

I tried by changing mongod.cfg with

  authorization: enabled
mongod --auth --port 27017 --dbpath /var/lib/myDatabase

from this tutorial Enable Access Control — MongoDB Manual
… but then it fails to connect to server.
Can you please advise how to set username and password requests for my database?

What error are you getting?
Can you connect from shell with new user id/PWD you created after enabling acces control?
Your connect string or app.js will change.Where have you defined user id & password in your file

Thanks for your reply.

  1. I stop MongoDB in Windows Services
  2. Change the mongod.cfg with security: authorization: enabled
    After these, I cannot reconnect MongoDB in Windows Services.
    In cmd:
mongod --auth --port 27017 --dbpath /var/lib/mongodb


mongo --port 27017 -u "myusername" --authenticationDatabase "admin" -p


MongoDB shell version v4.4.3
Enter password:
connecting to: mongodb://
Error: couldn't connect to server, connection attempt failed: SocketException: Error connecting to :: caused by :: No connection could be made because the target machine actively refused it. :
exception: connect failed
exiting with code 1

You say you modified mongod.cfg but you are starting mongod from command line?
You have to check why your mongod did not start from service
Also donot run multiple mongods on same port
I would suggest not to disturb your default mongod running on port 27017 instead create another mongod with different dbpath,logpath,port etc and do your authentication exercise on it

1 Like

Somehow it is working partially.
With mongod.cfg authentication, mongodb service could be started in Windows Services.
In command line:

mongo --port 27017 -u "username" -p "password" --authenticationDatabase "admin"


MongoDB shell version v4.4.3
connecting to: mongodb://
Error: Authentication failed. :
exception: connect failed
exiting with code 1

In app js


Database can be reached.

It is working now fully,
In command line I just wrote mongo and use myDatabase then db.auth("username","password")
gave me access to data