-1

I have a function as

 var emailExists = function (email) {
   mongoose.model('User', UserSchema).
    count({
        email: email
    }, function (err, count) {
        if (err) console.log(err);
        return count;// how can i return this count
    });
 };

in another function i call emailExists

 var total = emailExists(email)
 console.log(total); // this gives undefined now 

How can i get the return value from the anonymous function

EDIT: After adding callbacks from suggestions below

var emailNotExists = function (email, _callback) {
 mongoose.model('User', UserSchema).
    count({
        email: email
    }, function (err, count) {
        if (err)
            return _callback(err, null);
        return _callback(null, ((count == 0) ? true : false));
    });
};

Function where it is called

   UserSchema.path('email').validate(function (email) {
   // I need to return true or false value from this function
   // on true the validation will success
   // on false "Email is registered" message will get fired
   emailNotExists(email, function (err, total) {

       // I can retrieve the True/false value here           
       console.log(total);
   });
  }, 'Email is registered');
Sami
  • 3,926
  • 1
  • 29
  • 42
  • 3
    Is `mogoose.model` an asynchronous function? If so, anything that depends on the result of the callback function has to be done _in_ the callback. – Barmar Feb 01 '14 at 13:02
  • @Barmar please see my edited question. I hope I am clear this time. – Sami Feb 01 '14 at 13:29
  • Your first `return _callback(count)` is missing an argument to the callback. – Barmar Feb 01 '14 at 13:33
  • @Barmar edited. I just want to return true/false from the emailNotExists() call in UserSchema.path.validate function. How can I do that – Sami Feb 01 '14 at 13:47
  • If you know what "asynchronous" means, it should be obvious why that can't work. – Barmar Feb 01 '14 at 13:52

3 Answers3

3

Pass in a callback function:

var emailExists = function (email, _callback) {
   mongoose.model('User', UserSchema).
    count({
        email: email
    }, _callback);
 };

Then access the variable as follows:

emailExists(email, function(err, total) {
    console.log(total);
});
Matt Way
  • 32,319
  • 10
  • 79
  • 85
0

Use this code:

var total;
var emailExists = function (email) {
   mongoose.model('User', UserSchema).
    count({
        email: email
    }, function (err, count) {
        if (err) console.log(err);
        total = count;
    });
 };

Then you can access it: console.log(total);

leblma
  • 174
  • 7
0

Try this.

var emailExists = function (email) {
 var result;
   mongoose.model('User', UserSchema).
    count({
        email: email
    }, function (err, count) {
        if (err) console.log(err);
        result =count;// how can i return this count
    });
  return result;
 };
kjana83
  • 398
  • 3
  • 16