Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

328
Vistas
Create user only if not exists in MongoDB (simple example)

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.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda