Home > Mobile >  Checking the result of sampling mongoose
Checking the result of sampling mongoose

Time:11-02

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.

CodePudding user response:

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')
    }
};
  • Related