efkan
efkan

Reputation: 13227

How to assign query results to an object

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 });
    }
};

Upvotes: 0

Views: 85

Answers (1)

Pete.Mertz
Pete.Mertz

Reputation: 1301

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
        });

    });
}

Upvotes: 1

Related Questions