MongoDB – 使用nodejs驱动程序运行并行查询,并在最后一次查询完成时closures数据库连接

我需要使用node.js驱动程序并行运行多个针对MongoDB的查询。

目前我正在使用一个计数器,随着查询的完成而减less。 当计数器达到0意味着所有的查询已经完成,然后closures数据库连接。

在一个简单的情况下,并行运行2个查询的代码如下

var mongodb = require('mongodb'); var MongoClient = require('mongodb').MongoClient; var db; MongoClient.connect("mongodb://localhost:27017/company", function(err, database) { if(err) throw err; db = database; let collection = "resumes"; let numberOfParallelQueries = 2; let result = []; let finalCallback = (err, resp) => { if (err) throw(err); numberOfParallelQueries = numberOfParallelQueries -1; result.push(resp); if (numberOfParallelQueries == 0) { console.log(result); db.close() }; } db.collection(collection).find({"jobs": {$elemMatch: {"company": "CNA", position: "director"}}}).toArray(finalCallback); db.collection(collection).find({$and: [{"jobs.company": "CNA"}, {"jobs.position": "director"}]}).toArray(finalCallback); }); 

我的问题是,是否有更优雅的解决scheme。 我正在考虑ObservableforkJoin()方法中的一些东西。

提前致谢

这就是承诺 :

 var mongodb = require('mongodb'); var MongoClient = require('mongodb').MongoClient; var db; MongoClient.connect("mongodb://localhost:27017/company", function(err, database) { if(err) throw err; db = database; let collection = "resumes"; Promise.all([ queryPromise(collection, {"jobs": {$elemMatch: {"company": "CNA", position: "director"}}}), queryPromise(collection, {$and: [{"jobs.company": "CNA"}, {"jobs.position": "director"}]}) ]).then(function(result) { // result is an array of responses here db.close(); }).catch(function(err) { console.log(err); db.close(); }); function queryPromise(collection, query) { return new Promise(function(resolve, reject) { db.collection(collection).find(query).toArray(function(err, resp) { if (err) { reject(err); } else { resolve(resp); } }); }) } });