1

I am new to backend dev. I am trying to check if there is already an existing user in the collection and console log 'no' if there is none. I do not have the indicated data in 'const b' but instead of 'no' I keep getting empty array in terminal.

const b = {email: "[email protected]", password: "wwww"}
MyModel.find(b)
    .then(exUs =>{
        if(exUs){
            console.log(exUs)
        } else {
            console.log("no")
        }          
    })

1 Answer 1

1

find always returns an cursor(which can be empty [] if no docs) ,so your if condition will always true ,and if there are zero docs it will print empty array [] (returns cursor never null).

const b = {email: "[email protected]", password: "wwww"}
MyModel.find(b)
    .then(exUs =>{
        if(exUs){ // this always returns true even if there are no docs as empty array[]
            console.log(exUs)
        } else {
            console.log("no")
        }          
    })

What you should do rather ?

This

const b = {email: "[email protected]", password: "wwww"}
MyModel.find(b)
    .then(exUs =>{

        if(exUs.length>0){
            console.log(exUs)
        } else {
            console.log("no")
        }          
    })

Or You can use findOne,it will return null if no doc is found and the very first doc if exists ,so your code will become

const b = {email: "[email protected]", password: "wwww"}
MyModel.findOne(b)
    .then(exUs =>{
        if(exUs){// checks for null here now
            console.log(exUs)
        } else { 
            console.log("no")
        }          
    })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.