使用Express和MongoDB从多个单独的集合中获取 [英] Fetch from multiple, separate, collections with Express and MongoDB

查看:101
本文介绍了使用Express和MongoDB从多个单独的集合中获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网站,需要从Mongo数据中显示一些数据.但是,我的问题是我需要来自两个集合的数据.完全独立且彼此无关的集合.

I have a site where i need some data from my Mongo data to be shown. 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});
      });
   });
});

当然,这很好用.但是我又如何获得第二个db.collection('colors').find();传递给模板呢?

And this, of course, works perfectly fine. But how do i get a second 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..

推荐答案

使用 异步 库,最适合这种情况.在需要运行彼此不依赖的多个任务并且当它们都完成时又要做其他事情的地方,应该使用 async.parallel() 方法.签名为async.parallel(tasks, callback),其中task是函数数组.

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. The signature is async.parallel(tasks, callback), where tasks is an array of functions.

它将立即并行运行所有功能,等待所有功能调用其任务回调,最后,当所有任务完成时,它将运行回调(最终回调).

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

这篇关于使用Express和MongoDB从多个单独的集合中获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆