If you're using Node.js 4+ which supports Promises, you can wrap the query in a promise.
queryPromise = function(findQueryCursor) {
return new Promise(function(resolve, reject) {
findQueryCursor.toArray(function(err, data) {
resolve(data);
});
});
};
Then, create an array of Promises consisting of queries:
promiseAr = [];
promiseAr.push(
queryPromise(
db.collection('dbname').find(query1)
)
);
promiseAr.push(
queryPromise(
db.collection('dbname').find(query2)
)
);
Then call
Promise.all(promiseAr)
.then(function(dataArray) {
// results of query1 in dataArray[0]
// results of query2 in dataArray[1]
})
.catch(function(err) {
// catch errors
});
The queries will be sent in parallel to MongoDB, and the ".then" function will be called after all the queries have completed.
The reason you have to do this is because the .find() function returns a cursor, and then you have to call .toArray() to retrieve the data. .toArray() itself is asynchronous, so you have to wrap it in a Promise if you want to use Promise.all.