First of all, I'm an absolute beginner, so be gentle please... I have some data stored in mongodb using mongoose model with express:
var fooSchema = new mongoose.Schema({
name: String,
bars: [{bar1},{bar2},{bar3},{bar4},{bar5}]
});
And then a route that needs to find one entry by Id, and add some user specific data to every member of array in that object, and render a page using that data:
app.get("/foo/:id", function(req,res){
Foo.findById(req.params.id, function(err, foo){
if(req.isAuthenticated()){
foo.bars.forEach(function(bar){
Baz.find({userId: req.user._id}, function(err, baz){
bar.data = baz.somedata;
console.log("inside: " + bar.data);
});
});
}
console.log("outside: " + foo.bars);
res.render("foo", {foo: foo});
});
});
But that data is not sent for rendering in my view foo.ejs file. I get foo object with no bar.data attached to it. And when I console.log it inside forEach loop it is there. I figured that the reason is that rendering is executed before my mongodb queries are (it console.logs "outside" string before "inside". But have no idea how to avoid it.