createUser(user, writeConcern?)
This method creates a new user for the database where the method runs. db.createUser() returns a duplicate user error if the user already exists on the database.
The following operation creates the dbUser in the database and gives the user the readWrite and dbAdmin roles.
use db
db.createUser({
user: "dbUser",
pwd: "password",
roles: [ "readWrite", "dbAdmin" ]
})
Approach 1: When user is not exist
MongoDB
db.createUser({user: "dbUser",pwd: "password",roles: [ "readWrite", "dbAdmin" ]})
Output:
Successfully added user: { "user" : "dbUser", "roles" : [ "readWrite", "dbAdmin" ] }
Approach 2: When the user already exists
MongoDB
db.createUser({user: "dbUser",pwd: "password",roles: [ "readWrite", "dbAdmin" ]})
Output:
uncaught exception: Error: couldn't add user: User "dbUser@products" already exists : _getErrorWithCode@src/mongo/shell/utils.js:25:13 DB.prototype.createUser@src/mongo/shell/db.js:1367:11 @(shell):1:1
No comments:
Post a Comment