1

I want to create a function to check if the user already has an account or not. I have created it like the code below.

function emailExistInDb(email) {
    var status
    var body = null

    User.findOne({email: email}), (error, user) => {
        if(error) {
            console.log("err : " + error)
            res.status(500).json({
                status: false,
                message: error.message
            })
            return { 
                'status' : null, 
                'body' : null 
            }
        } else {
            if (user == null) {
                status = false
            } else {
                status = true
                body = user
            }
            return { 
                'status' : status, 
                'body' : body 
            }
        }
    }
}

I have used this function like the code below.

router.post('/register', async (req, res) => {
    const encryptedPassword = await utils.encrypt(req.body.password)
    const emailExist = emailExistInDb(req.body.email)
    if (emailExist.status) {
        res.json({
            status: true,
            message: "email already exist",
            user: emailExist.body
        })
    } else {
        try {
            const user = User({
                name: req.body.name,
                email: req.body.email,
                password: encryptedPassword
            })
    
            var newUser = await user.save()
            console.log(newUser)
    
            res.json({
                status: true,
                message: "user successfully created",
                user: newUser
            })
        } catch (error) {
            res.status(500).json({
                status: false,
                message: error.message
            })
            console.log("err : " + error.message)
        }  
    }  
})

But it's giving me an error.

    if (emailExist.status) {
                   ^

TypeError: Cannot read properties of undefined (reading 'status')

Please guide me what is the right way to do so. I am beginner at NodeJS. I have followed the link below to do so.

https://www.javascripttutorial.net/javascript-return-multiple-values/

IMANUL SIDDIQUE
  • 133
  • 1
  • 8
  • 1
    Other than that issue, the way you're returning multiple values from a function is correct: You return something that can contain multiple values, in your example an object. (Other options are an array or a Map, but object and array are the two popular choices for the situation above.) – T.J. Crowder Mar 10 '22 at 07:36
  • 1
    @IMANULSIDDIQUE - No, please read the answers to the linked question. You've returned from the callback to `findOne`, not from `emailExistInDb`. – T.J. Crowder Mar 10 '22 at 07:36
  • Okkk... Now I got it. Thank you so much. – IMANUL SIDDIQUE Mar 10 '22 at 07:48

0 Answers0