how get return value (of mongoose query output within model.exports ) to a calling module

StackOverflow https://stackoverflow.com/questions/23228862

  •  07-07-2023
  •  | 
  •  

Question

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
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top