0

i'm new to node js, i'm using restify and mongoose. so, i try to return some value when i found the data and return null when data not found. here is my code:

getUsers = function (user, pass, urole){
      var data = '';
      Publisher.findOne({username:user, password:pass, role:urole},function(err, success){
         if (err){}
         if (!success){
           //when data not found
           data = 'null';
         }else{
           //when data found
           data = 'found'; 
         }
     });
     return data;
}

and i want to call the function and assign to the variable.

var user = getUsers(user,pass,urole)
console.log(user)

but the result is undefined.

lutfi
  • 65
  • 2
  • 8

1 Answers1

1

The findOne is async function, please put return data into the callback function, also return date through callback function

getUsers = function (user, pass, urole, callback){
      var data = '';
      Publisher.findOne({username:user, password:pass, role:urole},function(err, success){
         if (err){}
         if (!success){
           //when data not found
           data = 'null';
         }else{
           //when data found
           data = 'found'; 
         }
         callback && callback(data);
     });
}

getUsers(user, pass, urole, function(data) {
    console.log(data);
});
zangw
  • 43,869
  • 19
  • 177
  • 214
  • i already tried this one. but when i call function getUsers, like : var data = getUsers(username, password, role); console.log(data); it keep returning "undefined". :'( – lutfi Feb 26 '16 at 09:26
  • thank for your response :D,... one more thing, can store the variable data to other variable? because i want to use it in the other function for example, i want to put the var "data" to var "xxx" how i can assign the value of data to xxx? thanks anyway – lutfi Feb 26 '16 at 10:33