node.js - node+express的后台,ejs模版引擎,mongodb,在路由中如何把不同表的查询结果render出去?
天蓬老师
天蓬老师 2017-04-17 13:34:56
0
3
613

比如我要做一个博客详情页,我会查文章表,然后将文章标题、作者、内容render出去,这就完成了一个路由请求。但如果我想在同一个页面再显示文章点击量排行榜,就需要另一个查询,如何才能做到render两个或以上mongodb查询的内容?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
伊谢尔伦

First define two different query methods:

var findContent = function(db, callback) {
       var cursor = db.collection('xxx').find({xx,xxx});
       ......(在这里边把content的查询结果放到变量里边)
   }

   var findRanking = function(db, callback) {
       ......(把ranking的查询结果放到变量里边)
   }

MongoClient.connect(url, function(err, db) {
    findContent(db, callback(){});
    findRanking(db, callback(){});
})

router.get('/xxx', function(req, res, next) {
        res.render('ejsFileName', {content: content, ranking: ranking});
})

You can try this method, I think it can meet your requirements

伊谢尔伦

The problem encountered by the poster should be that he performed an asynchronous data query, and at the same time, the second query relied on the results of the first query . Let’s just look at the code!


  var sql = 'xxxxxxx';
  async.waterfall([function (cb) {
    mysql.connection.query(sql, function (err, result) {
      if (err) {
        console.log(err);
        throw err;
      }
      var response = [];
      //此处省略数据处理逻辑
      cb(null, response);
    });
  }, function (result, cb) {
    async.eachSeries(result, function iterator(item, callback) {
      var sql = 'x'x'x'x'x'x'x'x'x'x';
      mysql.connection.query(sql, function (err, commentResult) {
        if (err) {
          console.log(err);
          throw err;
        }
        var formatResult = [];
        _.each(commentResult, function (item) {
          // 省略处理逻辑
          formatResult.push(item);
        });
        if (commentResult.length) {
          //xxxxx 省略处理逻辑
        }
        callback();
      });
    }, function done(err) {
      console.log("err: " + err);
      cb(null, result);
    });
  }], function (err, results) {
    cb(null, {
      "msg": "查询成功",
      "result": 1,
      "data": results
    });
  });

The above code mainly uses async middleware

Ty80

Save the content queried at each step in the same object, and then render it out. It’s very simple!!

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template