如何在mongoose中进行聚合和填充

3

我在填充“Main”集合方面遇到了问题,分组工作得很好,但我真的不知道如何在聚合后填充或查找。我相信我在这里进行了模型转换或类似操作:

Main.aggregate([
      {$match : query},
      {
        $group:{
          _id: queryGroupBy,
          activated: {$sum: '$activated'},
          componentTitle: {$first:'$componentTitle'},
          titlePrefix: {$first:'$titlePrefix'},
          operator_name: {$first:'$operator_name'}
        }
      },
      {
        $project:{
          _id: '$_id',
          summation: '$activated',
          componentTitle: '$componentTitle',
          titlePrefix: '$titlePrefix',
          operator_name: '$operator_name'   
        }
      }],
      function(err,results) {
        if (err) throw err;
        result = results.map(function(doc) { 
          doc._id = doc._id,
          doc.activated = doc.activated,
          doc.componentTitle = doc.componentTitle,
          doc.titlePrefix = doc.titlePrefix,
          doc.operator_name = doc.operator_name,
          doc.fssStatusFDD = "",
          doc.dateUpdated = "",
          delete doc._id;
          delete doc.summation;

            var _main = new Main();
            _main = doc;
            console.log('test3');
            return _main
            });
        Main.populate( results, { "path": "operator_name" }, function(err,results) {
            if (err) throw err;
            console.log( JSON.stringify( results, undefined, 4 ) );
        });

        console.log('good');
        return res.send(results);
    });

欢迎并感谢任何建议。

1个回答

10

找到了答案,看起来这个方法会有用。希望能帮到你。

    Main.aggregate([
  {$match : query},
  {
    $group:{
      _id: queryGroupBy,
      activated: {$sum: '$activated'},
      componentTitle: {$first:'$componentTitle'},
      titlePrefix: {$first:'$titlePrefix'},
      operator_name: {$first:'$operator_name'}
    }
  },
  {
    $project:{
      _id: '$_id',
      summation: '$activated',
      componentTitle: '$componentTitle',
      titlePrefix: '$titlePrefix',
      operator_name: '$operator_name'   
    }
  }],
  function(err,results) {
    Main.populate( results, { "path": "operator_name" }, function(err,results) {
        if (err) throw err;
        console.log( JSON.stringify( results, undefined, 4 ) );
        console.log('good');
        return res.send(results);
    });

});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接