Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 853
Newbie Avatar asked Oct 15 '13 21:10

Newbie


People also ask

What MongoDB is used for?

MongoDB is a document database used to build highly available and scalable internet applications. With its flexible schema approach, it's popular with development teams using agile methodologies.

Is MongoDB better than SQL?

Conclusion. MongoDB is a database that is more advanced and capable of handling big data with dynamic schema features. SQL Server is an RDBMS that is used to manage the relational database system and offers end-to-end business data solutions. In the case of unstructured data MongoDB is a good choice.

What is difference between SQL and MongoDB?

SQL databases are used to store structured data while NoSQL databases like MongoDB are used to save unstructured data. MongoDB is used to save unstructured data in JSON format. MongoDB does not support advanced analytics and joins like SQL databases support.

Is MongoDB a database or DBMS?

MongoDB (link resides outside IBM) is an open source, nonrelational database management system (DBMS) that uses flexible documents instead of tables and rows to process and store various forms of data.


1 Answers

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

like image 86
Newbie Avatar answered Oct 03 '22 23:10

Newbie