mongoose count()方法查询的结果如何以数组返回?

新手上路,请多包涵

我想用mongoose的count方法查询stations集合里各个部门的数量,push进一个数组然后返回给Echarts,可是响应的却是空的数组,请教各位大神应该怎么解决?

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);
});
阅读 5k
2 个回答
✓ 已被采纳新手上路,请多包涵
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解决了

用Aggregation吧,很好实现。你这样得查n次,用aggregation只用一次查出所有。以下是shell示例(并不太熟悉mongoose...)

let department = []
db.stations.aggregate([
    {$group: {_id: "$dept", count: {$sum: 1}}}
]).forEach(doc => {
    department.push(doc.count);
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题