0

i tried with this code but i can't get value of variable

var haveemail = 0; 

collection.count({email: req.body.email}, function (error, count,callback)                 { 
    console.log(count); 
    haveemail = count; 
}); 
console.log(haveemail)
Nir Levy
  • 12,750
  • 3
  • 21
  • 38

1 Answers1

0

Node.js works asynchronously, which means that right after collection.count() starts running, your console.log() call starts, most probably before the count call ends and before your variable is set.

you should move the console.log call to inside the callback, to make sure it happens after haveemail variable is set:

var haveemail = 0; 

collection.count({email: req.body.email}, function (error, count,callback) 
{ 
    console.log(count); 
    haveemail = count; 
    console.log(haveemail);
}); 
Nir Levy
  • 12,750
  • 3
  • 21
  • 38
  • i agree with you , actually i want count value out side collection.count thats why i store count value in haveemail but i cant got it – Dharmesh7980 Sep 30 '16 at 08:34
  • @Dharmesh7980 - whatever you want to do with this variable outside the function - you have to do it inside, or use `promises` or `async` library. Otherwise you can't count on it to be set on time. See this guide, it's quite good: https://blog.risingstack.com/node-hero-async-programming-in-node-js/ – Nir Levy Sep 30 '16 at 08:45