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
Here's the syntax for a mongodb, mongoose, node setup.
Create the database user in the admin database from the mongo shell
use admin
db.addUser( { user: "mydbuser", pwd: "mypassword", roles: [ ] } )
Create the database and add the user - the userSource indicates that the credentials are defined in the admin database
use mydb
db.addUser( { user: "mydbuser", userSource: "admin" , roles: [ "readWrite" , "dbAdmin"] } )
Specify the auth parameter in the mongoose connection string
var myDB = mongoose.createConnection("mongodb://mydbuser:mypassword@myipaddress:27017/mydb" ,{auth:{authdb:"admin"}});
the option {auth:...} is what specifies that the user account must be authenticated against the admin db.
Similarly to connect to the database from the mongo shell
mongo myipaddr:27017/mydb -u "mydbuser" -p "mypassword"
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
This can also can be simplified by modifying the connection string in the mongodb itself:
For eg: mongodb://username:password@IP:Port/mydbname?authSource=admin since mongoose supports this connection string provided by mongodb https://docs.mongodb.com/manual/reference/connection-string/#urioption.authSource