【问题标题】:Send multiple DB query results to a single view using Express使用 Express 将多个数据库查询结果发送到单个视图
【发布时间】:2017-03-10 17:40:53
【问题描述】:

我有一个仪表板视图 (dashboard.jade),它将显示两个具有不同信息的面板,所有这些信息都应该从数据库中检索,然后发送到视图。

假设我有一个定义了两个操作的路由文件 (document.js):

exports.getAllDocuments = function(req, res){
    doc = db.model('documents', docSchema);

    doc.find({}, function(err, documents) {
        if (!err) { 
            // handle success
        }
        else { 
            throw err;
        }
    });
};

exports.getLatestDocumentTags = function(req, res){
    tags = db.model('tags', tagSchema);

    tags.find({}, function(err, docs) {
        if (!err) { 
            // handle success
        }
        else { 
            throw err;
        }
    });
};

这些函数仅用于从数据库中检索数据。

现在我想从我的dashboard.js 路由文件中的exports.index 函数下将这些数据发送到仪表板视图,并在其中呈现我的仪表板视图。

问题是,由于数据库调用将是异步的,所以在调用视图之前我无法访问数据。

我想我可以有一个动作,简单地完成我所有的数据库调用,并通过回调将所有数据一次传送到视图,但这会使我的数据检索动作不可重用。

我真的很困惑如何正确解决这个问题,可能我把这个异步的东西弄错了。有人可以给我一些关于如何正确执行此操作的提示吗?

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    这里有一些东西可以激起你的兴趣。

    //Check out the async.js library
    var async = require('async');
    
    //Set up your models once at program startup, not on each request
    //Ideall these would be in separate modules as wel
    var Doc = db.model('documents', docSchema);
    var Tags = db.model('tags', tagSchema);
    
    function index(req, res, next) {
        async.parallel({ //Run every function in this object in parallel
        allDocs: async.apply(Doc.find, {}) //gets all documents. async.apply will
        //do the equivalent of Doc.find({}, callback) here
        latestDocs: async.apply(Tags.find, {})
        ], function (error, results) { //This function gets called when all parallel jobs are done
          //results will be like {
          //  allDocs: [doc1, doc2]
          //  latestDocs: [doc3, doc4]
          // }
          res.render('index', results);
        });
    }
    exports.index = index;
    };
    

    尝试更多教程。如果您还没有对 node 中异步编程如何工作的“哈哈”时刻,请继续阅读有指导的手持教程,然后再尝试在没有指导的情况下编写全新的程序。

    【讨论】:

      【解决方案2】:
      //Check out the async.js library and mangoose model
      var mongoOp     =   require("./models/mongo");
      var async = require('async');
      
      
      router.get("/",function(req,res){
          var locals = {};
          var userId = req.params.userId;
          async.parallel([
              //Load user Data
              function(callback) {
                   mongoOp.User.find({},function(err,user){
                      if (err) return callback(err);
                      locals.user = user;
                      callback();
                  });
              },
              //Load posts Data
              function(callback) {
                      mongoOp.Post.find({},function(err,posts){
                     if (err) return callback(err);
                      locals.posts = posts;
                      callback();
                  });
              }
          ], function(err) { //This function gets called after the two tasks have called their "task callbacks"
              if (err) return next(err); //If an error occurred, we let express handle it by calling the `next` function
              //Here `locals` will be an object with `user` and `posts` keys
              //Example: `locals = {user: ..., posts: [...]}`
               res.render('index.ejs', {userdata: locals.user,postdata: locals.posts})
          });
      

      【讨论】:

        猜你喜欢
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-11
        • 1970-01-01
        • 2015-09-25
        • 2017-09-05
        相关资源
        最近更新 更多