Home > Software engineering >  Create user only if not exists in MongoDB (simple example)
Create user only if not exists in MongoDB (simple example)

Time:12-06

I'm newby to MongoDB and .js.

I have a simple add_app_user.js script with the following content:

# MongoDB shell version v4.2.17
# Set the database to 'testdb'.
db = db.getSiblingDB('testdb');

# Create new user.
db.createUser(
   {
     user: "testuser",
     pwd: "testpass",
     roles: [ "readWrite" ]
   }
);

This works fine for the first time (when such a user doesn't exist).

I need to make it idempotent.

I couldn't find an simple to understand script that will check for the "testuser" availability in the "testdb" and run my script block only if the check fails.

CodePudding user response:

Try this:

if (db.getUser("testuser") == null) {  
   db.createUser(
     {
     user: "testuser",
     pwd: "testpass",
     roles: [ "readWrite" ]
     }
   );
}

NB, usually users are created in admin database. Actually I don't know any reason why they should be created anywhere else.

  • Related