5

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 in another database but examples of syntax are hard to come by.

I was on the verge of posting a question when i finally figured it out. Here goes in case it helps someone else

Newbie
  • 525
  • 1
  • 6
  • 16

2 Answers2

8

Here's the syntax for a mongodb, mongoose, node setup.

  1. Create the database user in the admin database from the mongo shell

    use admin

    db.addUser( { user: "mydbuser", pwd: "mypassword", roles: [ ] } )

  2. 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"] } )

  3. 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.

  4. 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

Vince Bowdren
  • 8,326
  • 3
  • 31
  • 56
Newbie
  • 525
  • 1
  • 6
  • 16
  • 3
    userSource field is removed from v2.6 in the createUser method. Can you guide me to the createUser method equivalent of the post? – wdphd Jul 20 '14 at 14:26
  • 2
    This information is no longer correct in recent versions of mongo. – ccnokes Aug 18 '15 at 03:31
4

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