0

I am trying to transfer results data from query function to an object. console.log(results) line returns 'undefined' result. What should I do?

module.exports = {

    show: function(req, res) {

        var results;
        User.native(function(err, User) {

            if(err) {                    
                console.log("There is no exist a User by _id");
            }

            User.findOne({'_id' : req.param('id')}, 
                    function(err, user) {
                      results = user;
            });

        });

        console.log(results);
        return res.view({ stuff : results });
    }
};
efkan
  • 12,991
  • 6
  • 73
  • 106

1 Answers1

1

You have an async issue, the callback from findOne isn't necessarily executed in line with the rest of the code, so you get to the console.log(results) before results = user gets called. You'd want to change it to something like this:

show: function(req, res) {

    var results;
    User.native(function(err, User) {

        if(err) {                    
            console.log("There is no exist a User by _id");
        }

        User.findOne({'_id' : req.param('id')}, 
                function(err, user) {
                  results = user;

                 console.log(results);
                 // Send response or make a callback here
        });

    });
}
Pete.Mertz
  • 1,302
  • 2
  • 18
  • 34
  • Thank you for your help. Because I can't use 'results' out of the native function. – efkan Jun 27 '14 at 21:07
  • if you really need to get things done serially, you could also consider using the async library: https://github.com/caolan/async – Pete.Mertz Jun 29 '14 at 01:03