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

前端 未结 2 915
执念已碎
执念已碎 2021-02-10 06:26

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

相关标签:
2条回答
  • 2021-02-10 06:52

    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

    0 讨论(0)
  • 2021-02-10 06:53

    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

    0 讨论(0)
提交回复
热议问题