Reputation: 2128
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
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