Reputation: 195
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?
Upvotes: 1
Views: 1051
Reputation: 63663
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);
}
);
});
Upvotes: 0
Reputation: 169383
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.
Upvotes: 2