0

This is my first try at javascript and I am trying to validate if the email is already present in the database or not. But before my find query the "if" statement is working. If you have a better way to do this, feel free to share. Thank you for your time.

router.post('/register',[
check('name').not().isEmpty(),
check('dob').not().isEmpty(),
check('gender').not().isEmpty(),
check('email').not().isEmpty(),
check('email').isEmail(),
check('username').not().isEmpty(),
check('password').not().isEmpty(),
check('password2').not().isEmpty()],function(req,res){

const name = req.body.name;
const dob = req.body.dob;
const gender = req.body.gender;
const email = req.body.email;
const username = req.body.username;
const password = req.body.password;

var temp;
var query = {email: email}
User.findOne(query,function(err,user){
 if(err)
 {
  message: err.message;
  return;
 }
if(user)
{
  temp=user.email;
}
});

 //THIS IS CHECKING temp BEFORE user CHANGES THE VALUE OF temp
 if(temp !== null)
 {
  req.flash('danger',"Email already exists.");
  res.redirect('/users/register');
  return;
 }
  • `findOne` is asynchronous, you won't be able to check to check the value until you actually get it from the db (which is not instant). To not block everything until you get it, it uses a "callback", a function only called once the result has arrived. You'll have to move your if inside the callback function (the one where you assign `temp`), or another one called from inside that function – Bali Balo Jul 05 '19 at 22:31
  • with the reference to my code....can you please show me how to do that ??...thanks in advance – Jayesh Menghani Jul 06 '19 at 00:28
  • It's been mentioned in the other responses but [here is an example](https://jsfiddle.net/5t61qcxn/) - it's your current code to which I added a function `keepGoing` that would contain the rest of your code. Note: there are plenty of ways to achieve something similar, this is just one way that works, not necessarily the best. It is mostly a matter of conventions and coding style. Choose what you think is the easiest to understand and maintain. – Bali Balo Jul 08 '19 at 13:30

1 Answers1

0

Well I am not overly familiar with router but I assuming you are querying an api or server as you are doing a post?

If so this is common functionality because you are calling an asynchronous method but you are expecting it to act like a synchronous method. Basically you need to either use async/await or promises to get the value of the item once it returns from the async call.

So it would be like

User.findOne(query, function).then(function(response){
   var result=response.data;

//Do something with the data
});
MattE
  • 1,044
  • 1
  • 14
  • 34