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

139
Vistas
Checking the result of sampling mongoose

In the study, I got stuck at one point. Trying to check if a value exists in MongoDB db collection documents using Mongoose. I have a separate function that searches for a DB entry using findOne. If we remove everything unnecessary from the code, it looks something like this:

const checkUserExist = async (userName) => {
  return await userModel.findOne ({userName});
};


const validateRegistrationData = (inputData) => {

const {userName} = inputData;

const userExist = checkUserExist (userName);

if (userExist) {
console.log ('User found')
}
 else {
 console.log ('User not found')
}
};

The problem is that it always returns true in this case.

I tried a couple more options:

 if (! userName) {
}
 if (userName === null) {
}
if (userName! == null) {
}
if (userName === undefined) {
}
if (userName! == undefined) {
}

Document Model:

const userSchema = new Schema (
{
userName: {type: String, unique: true, required: true},
name: {type: String, required: true},
email: {type: String, unique: true, required: true},
encryptedPassword: {type: String, required: true},
},
);

This is clearly a newbie mistake, but I did not find any clear information on this on the network.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It's because you're not awaiting the checkUserExist() method. Because that method returns a promise, your if statement will always result to true. If you convert validateRegistrationData() to an async method and await the call to checkUserExist() it should work as expected.

Something like this:

const validateRegistrationData = async (inputData) => {
    const {userName} = inputData;
    const userExist = await checkUserExist(userName);

    if (userExist) {
        console.log ('User found')
    } else {
        console.log ('User not found')
    }
};
about 4 years ago · Juan Pablo Isaza 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