0

Hey I'm trying to change the value of a variable outside from Mongoose query functions within an express function. Here is an example of my code:

//Register
router.post('/register', (req, res, next) => {
  let newUser = new User({
    name: req.body.name,
    email: req.body.email,
    username: req.body.username,
    password: req.body.password
  });

  var exists;

  User.findOne({
            email: req.body.email
        }, function (err, existingUser) {

            if (existingUser) {
                console.log('Email exists');
                exists = true;
          }
      });
  User.findOne({
            username: req.body.username
        }, function (err, existingUser) {

            if (existingUser) {
                console.log('Username exists');
                exists = true;
          }
      });

  console.log(exists);
  if (exists == true) {
    res.json({
      success: false,
      msg: 'Email or username is already registered'
    })
  }
});

The variable 'exists' is still undefined even when the ExistingUser condition is true. How do I make a change to to the variable or is the a better way to do it?

Axelotl
  • 13
  • 2

1 Answers1

0
`//Register
router.post('/register', (req, res, next) => {
  let newUser = new User({
    name: req.body.name,
    email: req.body.email,
    username: req.body.username,
    password: req.body.password
  });

  var exists;

  User.findOne({
    '$or': [{
      email: req.body.email
    }, {
      username: req.body.username
    }]
  }, function (err, existingUser) {
    if (existingUser) {
      console.log('Email exists');
      exists = true;
    }
    console.log(exists);
    if (exists == true) {
      res.json({
        success: false,
        msg: 'Email or username is already registered'
      })
    }
  });

})`

Try the above code.