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

206
Views
How to return multiple variable from a nodeJS function and use it?

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/

about 4 years ago · Juan Pablo Isaza
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!