使用mongodb保存node.js的异步特性的多个数据

saving multiple data with async nature of node.js with mongodb

本文关键字:数据 异步 保存 node js 使用 mongodb      更新时间:2023-09-26

我有一个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的东西。下面是一个简单的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
    });
});