Node JS, express, Mongoose, nested queries

Problem

I have a set of nested queries with express/mongoose, pretty much like so:

app.get(..., function(...) {

   Schema1.query(..., function(..., res1) {

      for ( var key in res1 ) {
           Schema2.query(..., function(..., res2) {
             data[key].appendedAttribute = res2.somedata;
            });
      }

      res.render(..., data);
   });

});

Which doesnt work, that is, appendedAttribute is never appended to the dataset. What am I doing wrong?

Problem courtesy of: Gunnar2k

Solution

Using after

app.get(..., function(...) {
    Schema1.query(..., function(..., res1) {
        var cb = after(Object.keys(res1).length, function () {
            res.render(..., data);    
        });

        for (var key in res1) {
            Schema2.query(..., function(..., res2) {
                data[key].appendedAttribute = res2.somedata;
                cb();
            });
        }
    });
});

Basically you must only fire the res.render call after the second query has finished.

Solution courtesy of: Raynos

Discussion

Using Step:

app.get(..., function(...) {
  var data;
  Step(
    function first_query() {
      Schema1.query(...,this);
    },
    function multiple_queries(err, res1) {
      for (var key in res1) {
        Schema2.query(..., function(..., res2) {
          data[key].appendedAttribute = res2.somedata;
          this.parallel(); // make sure callback gets executed only after all the queries are executed
        });
      }     
    },
    function render() {
      res.render(..., data);
    }
  );
});
Discussion courtesy of: alessioalex

This recipe can be found in it's original form on Stack Over Flow.