简体   繁体   English

使用Express和MongoDB从多个独立的集合中获取

[英]Fetch from multiple, separate, collections with Express and MongoDB

I have a site where i need some data from my Mongo data to be shown. 我有一个网站,我需要显示我的Mongo数据中的一些数据。 My problem, however, is that i need data from two collections. 然而,我的问题是我需要来自两个集合的数据。 Collections that are completely separate and have nothing to do with each other. 完全独立且彼此无关的集合。

Right now i have this in my routes for my profile-page: 现在我在我的路线中有我的个人资料页面:

router.get('/profile', function(req, res,next) {
   var resultArray = [];

   mongo.connect(url, function(err, db) {
      var cursor = db.collection('users').find();
      cursor.forEach(function(doc, err) {
         resultArray.push(doc);
      }, function() {
         db.close();
         res.render('profile/index', {users: resultArray});
      });
   });
});

And this, of course, works perfectly fine. 当然,这非常合适。 But how do i get a second db.collection('colors').find(); 但是我如何获得第二个db.collection('colors').find(); to be passed along to my template too? 要传递给我的模板吗?

I'm sure it's something trivial, and me just not quite having the full grasp of things, but yeah.. I'm stuck.. 我确定这是微不足道的,我只是不完全掌握事物,但是是的......我被卡住了......

Use the async library which is best suited for this scenario. 使用最适合此方案的异步库。 Where you need to run multiple tasks that do not depend on each other and when they all finish do something else, you should use async.parallel() method. 如果您需要运行多个不依赖于彼此的任务,并且当它们全部完成其他操作时,您应该使用async.parallel()方法。 The signature is async.parallel(tasks, callback) , where tasks is an array of functions. 签名是async.parallel(tasks, callback) ,其中tasks是一个函数数组。

It will immediately run all the functions in parallel, wait for all of them to call their task callback, and finally when all tasks are complete it will run callback (the final callback). 它将立即并行运行所有函数,等待所有函数调用它们的任务回调,最后当所有任务完成后,它将运行回调(最终回调)。

The following example demonstrates how this could be adapted for your use case: 以下示例演示了如何根据您的用例调整它:

router.get('/profile', function(req, res, next) {
    mongo.connect(url, function(err, db) {
        var locals = {};
        var tasks = [
            // Load users
            function(callback) {
                db.collection('users').find({}).toArray(function(err, users) {
                    if (err) return callback(err);
                    locals.users = users;
                    callback();
                });
            },
            // Load colors
            function(callback) {
                db.collection('colors').find({}).toArray(function(err, colors) {
                    if (err) return callback(err);
                    locals.colors = colors;
                    callback();
                });
            }
        ];

        async.parallel(tasks, function(err) { //This function gets called after the two tasks have called their "task callbacks"
            if (err) return next(err); //If an error occurred, let express handle it by calling the `next` function
            // Here `locals` will be an object with `users` and `colors` keys
            // Example: `locals = {users: [...], colors: [...]}`
            db.close();
            res.render('profile/index', locals);
        });
    });
});

Try this code: 试试这段代码:

router.get('/profile', function(req, res,next) {
   var resultArray = {
                      users : [],
                      colors : []
                     };

   mongo.connect(url, function(err, db) {
      var cursor = db.collection('users').find();
      cursor.forEach(function(doc, err) {
         resultArray.users.push(doc);
      }
      var colors = db.collection('colors').find();
      colors.forEach(function(doc,err){
          resultArray.colors.push(doc);
       }, function() {
         db.close();
         res.render('profile/index', {users: resultArray.users, colors: resultArray.colors});
      });
   });
});

Didn't have time to check it, but I'm pretty sure that it would work. 没有时间检查它,但我很确定它会起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM