Ad

Mongoose Find Query With Multiple Condition

- 1 answer

I am trying to verify verification code while registering user. Query have multiple conditions. if document is returned, then verification code is verified else not. Problem from below snippet, it always satisfy if(foundUser) although document is not returned.

UserModel
        .find({
            email,
            verificationCode: code
        },
        (err, foundUser) => {
            if(err) {
                return res.json({msg: "Error"})
            }
            else {
                console.log('foundUser', foundUser)
                if(foundUser) {
                    return res.json({msg: "found email + code"})
                }
                else {
                    return res.json({msg: "No email & code matched"})
                }

            }
        })
Ad

Answer

foundUser can be written in 3 ways

  if (foundUser.length !== 0) {}
  if (!foundUser.length) {}
  if (foundUser.length > 0) {}

Choose the one which suits you best.

I would suggest option number 2

UserModel
            .find({
                email,
                verificationCode: code
            },
            (err, foundUser) => {
                if(err) {
                    return res.json({msg: "Error"})
                }
                else {
                    console.log('foundUser', foundUser)
                    if (!foundUser.length) {
                        return res.json({msg: "found email + code"})
                    }
                    else {
                        return res.json({msg: "No email & code matched"})
                    }

                }
            })
Ad
source: stackoverflow.com
Ad