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);

});


慕沐林林
浏览 1084回答 6
6回答

慕数据1385771

// 因为mongodb或者mongoose都是通过回调返回结果的,所以通过await实现同步数据let data = await Users.find();

慕数据1385771

// 因为mongodb或者mongoose都是通过回调返回结果的,所以通过await实现同步数据let data = await Users.find();

慕数据1385771

// 因为mongodb或者mongoose都是通过回调返回结果的,所以通过await实现同步数据下面的data就是数组的了let data = await Users.find();

慕数据1385771

 // 因为mongodb或者mongoose都是通过回调返回结果的,所以通过await实现同步数据let data = await users.find();这个data就是数组的了

PIPIONE

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);});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript