鍍金池/ 問答/數(shù)據(jù)庫  HTML/ mongoose count()方法查詢的結(jié)果如何以數(shù)組返回?

mongoose count()方法查詢的結(jié)果如何以數(shù)組返回?

我想用mongoose的count方法查詢stations集合里各個(gè)部門的數(shù)量,push進(jìn)一個(gè)數(shù)組然后返回給Echarts,可是響應(yīng)的卻是空的數(shù)組,請教各位大神應(yīng)該怎么解決?

router.get('/chart', function (req, res, next) {
  let depts = ['部門1', '部門2', '部門3', '部門4', '部門5',
    '部門6', '部門7', '部門8'];
  let department = [];
  for(let x in depts){
    stations.count({"dept": depts[x]}).exec(function (err, counts) {
      department.push(counts);
    });
  }
  res.json(department);
});
回答
編輯回答
萌小萌

用Aggregation吧,很好實(shí)現(xiàn)。你這樣得查n次,用aggregation只用一次查出所有。以下是shell示例(并不太熟悉mongoose...)

let department = []
db.stations.aggregate([
    {$group: {_id: "$dept", count: {$sum: 1}}}
]).forEach(doc => {
    department.push(doc.count);
});
2018年8月17日 21:08
編輯回答
扯不斷
let department = [];
  let asynQuery = () => {
    return new Promise( (resolve, reject) => {
      stations.aggregate([{$group: {_id: "$dept", count: {$sum: 1}}}]).exec(function (err, doc) {
        department.push(doc);
        resolve(department);
      });
    });
  }
  asynQuery().then(department=>{
    res.json(department)
  });

原來是異步的問題,通過Promise解決了

2018年1月29日 05:04