0
router.post("/register",validator.validate("createUser"), function(req,res){
   const register = User({
            fullname:fullname,
            contact:contact,
            email:email,
            password:bcrypt.hashSync(password, salt),
            role:check_user.if_user_exists()
        })
        register.save()    
 } 

The Below code is from check_user.js file

exports.if_user_exists= function(){
     User.findOne({role:"Admin"},function(err,data){
            if(data){
                console.log("Inside User"+data)                
                return "User"
            }else{                
                console.log("Inside Admin"+data)                
                return "Admin"
            }
    }) 
}

So the Problem i'm facing is, when the record is saved the role value is undefined, i think the problem is its not waiting for function to return value. Please help me out how to fetch the method value

Demo Test
  • 3
  • 1
  • Please see [How do I return the response from an aynchronous call](https://stackoverflow.com/q/14220321/438992), which this duplicates. – Dave Newton Jun 13 '21 at 12:45

1 Answers1

0

Change if_user_exists function to this.

exports.if_user_exists = function () {
    return new Promise((resolve, reject) => {
        User.findOne({ role: "Admin" }, function (err, data) {
            if (err) reject(err)
            if (data) {
                console.log("Inside User" + data)
                return resolve("User")
            } else {
                console.log("Inside Admin" + data)
                return resolve("Admin")
            }
        })
    })
}

Then change the saving logic to this.

router.post("/register", validator.validate("createUser"), async function (req, res) {
    let role = await check_user.if_user_exists()
    const register = User({
        fullname: fullname,
        contact: contact,
        email: email,
        password: bcrypt.hashSync(password, salt),
        role
    })
    register.save()
})
Anil Kumar
  • 84
  • 2
  • 3