javascript - 使用 mongodb 保存具有 Node.js 异步特性的多个数据

标签 javascript node.js mongodb express mongoose

我有一个 id 数组:

var ids = ['53asd3','53asd2','53asd5'];

每个id在mongodb中都有对应的文档。 我想通过填充每个对象的数据来生成一个对象,并将其保存在其他文档中。像这样:

{
    person: {   /* data from some collection populated with first id */},
    company : { /* data from some collection populated with first id */},
    employee : {/* data from some collection populated with first id */}
} 

我做了什么

var document = {}
models.persons.find({_id:'53asd3'},function(err,data){
    if(!err) {
        document['persons']=data;
        models.company.find({_id:'53asd2'},function(err,data){
            if(!err) {
                document['company']=data;
                models.employee.find({_id:'53asd2'},function(err,data){
                    if(!err) {
                        document['employee']=data;
                        document.save(function(err){ });
                    }
                });
            }
        });
    }
});

所以我只是使用回调来使用嵌套调用,并在某种程度上使其同步。我是否有机会并行执行所有这三个查找查询,然后执行保存命令?我实际上想利用 Node.js 的异步特性。有什么建议吗?

最佳答案

如果您不想包含外部库,您可以自己构建类似 async.parallel 的内容。下面是一个简单的并行函数的样子。实现 async 库中的其他函数可能是一个很好的练习。

var parallel = function () {
    var functs = arguments[0];
    var callback = arguments[1];

    // Since we're dealing with a sparse array when we insert the results,
    // we cannot trust the `length` property of the results.
    // Instead we count the results separately
    var numResults = 0;
    var results = [];
    var getCallback = function (i) {
        return function (err, res) {
            if (err) {
                callback(err)
            }
            else {
                results[i] = res;
                numResults += 1;

                if (numResults === functs.length) {
                    callback(null, results);
                }
            }
        }
    }

    functs.forEach(function (fn, i) {
        fn(getCallback(i));
    });
};


var getTest = function (timeout) {
    return function (callback) {
        setTimeout(function () {
            callback(null, timeout);
        }, timeout);
    }
};

parallel([getTest(99), getTest(1000), getTest(199)], console.log.bind(console));
>> null [99, 1000, 199]

那么根据你的情况,你可以做类似的事情

var findItem = function (collection, id) {
    return function (callback) {
        collection.find({
            _id: id
        }, callback);
    };
};

parallel([
    findItem(models.persons, '53asd3'),
    findItem(models.company, '53asd2'),
    findItem(models.employee, '53dsa2')
], function (err, results) {
    document.persons = results[0];
    document.company = results[1];
    document.employee = results[2];
    document.save(function (err) {
        // and so on
    });
});

关于javascript - 使用 mongodb 保存具有 Node.js 异步特性的多个数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23996585/

相关文章:

javascript - For 循环中的 getElementById

javascript - Express:为 app.use 抽象出中间件

node.js - 无法在 Ubuntu 中使用 Express.js

PHP Mongo 聚合匹配正则表达式

javascript - 使用带有悬停的 raphael.js 内存泄漏

javascript - 无法使用 Babel 单吨编译 TypeScript

javascript - 使用 ng-change 根据 AngularJS 中另一个下拉列表的选择来填充一个下拉列表

javascript - 无法停止nodejs中的递归settimeout函数

mongodb - 不坚持 Scala None's 而不是坚持为空值

Mongodb:由对等方重置连接