willium
willium

Reputation: 2128

Weird behavior with node/mongo/functions/scoping

I have this express.js route

app.get("/explore/:category?", checkCategory, function(req, res){   
     var params = new Array();
     params["path"] = req.route.path;

     Category.findOne({hash:category}, function (err, doc) {
         params["category"] = doc;
     });

     console.log(params);

when you're inside the findOne, the doc value, and params["category"] values are just fine. Outside of that scope however, it disappears and params["category"] becomes "undefined." Now after refreshing the page once, it returns to normal behavior, and seems to remain that way throughout the rest of the running of node.

Why does this behavior occur?

Upvotes: 0

Views: 63

Answers (1)

mtsr
mtsr

Reputation: 3142

This happens because the console.log gets called before the callback you pass to findOne. It works as expected if you change it like this:

Category.findOne({hash:category}, function (err, doc) {
    params["category"] = doc;
    console.log(params);
});

Also, see answers to similar questions like this one.

Upvotes: 2

Related Questions