Newbie
Newbie

Reputation: 535

MongoDB & Mongoose accessing one database while authenticating against another (NodeJS, Mongoose)

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

Upvotes: 5

Views: 4836

Answers (2)

cyril naves
cyril naves

Reputation: 51

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

Upvotes: 5

Newbie
Newbie

Reputation: 535

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

Upvotes: 8

Related Questions