Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!