0

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.

Denis B
  • 235
  • 1
  • 2
  • 9
  • Question was marked as duplicate, but i tried a solution from "original" question and i still have the same issue. – Denis B May 10 '18 at 13:38
  • Where? Where did you actually add `.lean()` to the query? That's right you actually did not. It's only the [top answer](https://stackoverflow.com/a/14510823/2313887) on the question so I can see how that can be difficult to miss. Also adding another "query" **inside** your loop just introduces another issue. Have another duplicate, but really you need to learn from the first one. Simply adding `lean()` would have fixed it. Now you've made it worse. – Neil Lunn May 10 '18 at 21:40
  • I added .lean() like this: `foo.findById(req.params.id).lean().exec(function(err, foo){..}` – Denis B May 11 '18 at 04:41
  • I tried to add `.lean()` in the second query too, but still have the same issue. I'm not sure what do you mean when you say I've made it worse? – Denis B May 11 '18 at 04:52
  • Second answer in header is what I was looking for... asynchronous code... thx – Denis B May 11 '18 at 05:01

0 Answers0