如何连接mongodb中两个集合的长度并获得一个variables中两个集合的总长度?

下面是我的code.i需要获得单个variables的两个集合的总长度。

audiofiles.find(),function(err,res){ console.log(res.length); var count1 = res.length; } videofiles.find(),function(err,res){ console.log(res.length); var count2 = res.length; } var totalcount = parseInt(count1+count2); console.log(totalcount); 

你有没有尝试过:

  var totalcount = parseInt(parseInt(count1)+parseInt(count2)); 

__

本地到全球的范围

 var count1; var count2; audiofiles.find(),function(err,res){ console.log(res.length); count1 = res.length; } videofiles.find(),function(err,res){ console.log(res.length); count2 = res.length; } var totalcount = parseInt(parseInt(count1)+parseInt(count2)); console.log(totalcount); 

注意:这是过于冗长,但它应该工作。 希望..

使用count()方法返回集合中文档的数量。 由于它是一个asynchronous方法,因此可以使用asynchronous库来获取两个调用返回的结果的总和,或者可以使用promise。

考虑node-async包的用例,其中包含许多用于处理类似情况的函数,使用瀑布API:

 var totalcount; async.waterfall([ function (callback) { audiofiles.count({}, function(err, res) { if (err) { return callback(err); } callback(res); }); }, function(count1, callback){ videofiles.count({}, function(err, count2) { if (err) { return callback(err); } totalcount = count1 + count2; callback(null, totalcount); }); } ], function (err, result) { if (err) throw err; console.log(result); // result = totalcount }); 

或使用承诺

 var totalcount, count1 = audiofiles.count(), count2 = videofiles.count(); Promise.all([count1, count2]) .then(function (counts) { function add(a, b) { return a + b; }; totalcount = counts.reduce(add, 0); console.log(totalcount); }) .catch(function (err) {}) 

没有上述,嵌套的asynchronous调用(不build议,因为它可能会创buildcallback地狱):

 var totalcount; audiofiles.count({}, function(err, count1) { if (err) throw err; videofiles.count({}, function(err, count2) { if (err) throw err; totalcount = count1 + count2; console.log(totalcount); }) })