1

For a project, I am working to get return value to main application module post validation of user and password from a mongoDB using mongoose. I am able to printout result post "User.findOne" using console.log (commented in code) but fail to pass this result to main module "app.js". I am getting "undefined" as output or initialised value of "result" if do in the User.js module.

Need help to know how to get return value (of "result" in below code) from User.js to app.js.

I am not looking for return this value using "res.send" as web response. which i found mostly while exploring google for the issue.

Thanks.

app.js

var user = require ('./User');
console.log(user.authentication("user","pass"));

User.js

var User = require('./models/Mongoose');

exports.authentication = function(user, pass){
  var query = {uid: user};
  var result;
  //var result = "None";
  User.findOne(query, function(err,obj) {
    if (err) {
      result = "error: find method";
    } else {
      if (obj != null) {
        if ( pass == obj.password) {
          //console.log("success: authorisation successful");
          result = "authentication successful";
        } else {
          //console.log("error: password incorrect");
          result = "authentication failed";
        }
      } else {
        result = "error: absent user";
      }
    }
  });
  return result;
};

Output of app.js:

undefined
Ajay
  • 1,255
  • 1
  • 17
  • 30

1 Answers1

3

You return result before User.findOne has any opportunity to give you something. Instead you should add a callback function to authentication method e.g.

exports.auth = function(user, pass, callback){
  User.findOne(...., function(err, user){
   var result = !!user;
   callback(err, result);
 });
}

Anyway, you should get used to asynchronous code to feel comfortable working with node. These tutorials are likely to help you: How do I get started with Node.js

Community
  • 1
  • 1
Eugene Kostrikov
  • 6,799
  • 6
  • 23
  • 25
  • Where is callback defined? The router? – michaelAdam Sep 02 '14 at 01:46
  • @michaelAdam Actually, it doesn't matter. You provide the callback yourself wherever you use `exports.auth`. It's nothing more than just a simple function that follows convention of expecting possible error as the first argument and result as the rest args. – Eugene Kostrikov Sep 02 '14 at 06:30