Node JS,express,Mongoose,嵌套查询

时间:2011-11-13 22:46:22

标签: javascript mongodb node.js express

我有一组带有express / mongoose的嵌套查询,非常类似:

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

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

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

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

});

哪个不起作用,也就是说,additionalAttribute永远不会附加到数据集。我做错了什么?

2 个答案:

答案 0 :(得分:2)

使用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();
            });
        }
    });
});

基本上,您必须在第二个查询完成后才启动res.render调用。

答案 1 :(得分:0)

使用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);
    }
  );
});