Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda