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/