【问题标题】:how to make aggregrate function dynamic using params in express and mongoose如何使用 express 和 mongoose 中的参数使聚合函数动态化
【发布时间】:2018-10-16 11:49:14
【问题描述】:

我在 mongoose 中使用聚合函数来获取一些数据,这里是静态实现

app.get("/male",function (req,res) {
  Record.aggregate([
    {
      $match: 
      {"gender": "male"}
    },
      {
         $group:{ 
            _id : "$type",
             total : {$sum : 1}
        }
      },{
      $sort: {_id: 1}
    }
      ]).exec((err,data) => {
            if (err) {console.log(err)} 

            res.json(data)

        })

})

我想让它完全动态,所以我尝试了这个

  app.get("/:query/:type/:match",function (req,res) {

  var match = req.params.match

  Record.aggregate([
    {
      $match: 
      {match : req.params.type}
    },
      {
         $group:{ 
            _id : "$"+req.params.query,
             total : {$sum : 1}
        }
      },{
      $sort: {_id: 1}
    }
      ]).exec((err,data) => {
        if (err) {console.log(err)}

              res.json(data)

        })

})

我调试了一下,ma​​tch似乎没有传入$match

如果我把静态变量而不是匹配它工作

这里是它的架构

   var mongoose = require('mongoose');

   var RecordSchema = new mongoose.Schema({

      type:String,
      gender:String,
      age:Number,
      timeSpent:Number,
      arrivedAt:Number

   })

   module.exports = mongoose.model("Record", RecordSchema);

【问题讨论】:

  • 尝试 [match] 而不是在查询中匹配。
  • 谢谢!它奏效了

标签: javascript mongodb express mongoose parameters


【解决方案1】:

试试这个方法:

app.get("/:query/:type/:match",function(req,res) {

  var match = req.params.match;
  var type= req.params.type;
  var query = "$"+req.params.query;
  var matchCriteria = {};
  matchCriteria[match]=type;


  Record.aggregate([
    {
      $match:matchCriteria
    },
    {
         $group:{ 
             _id : query,
             total:{$sum:1}
        }
    },{
      $sort: {_id: 1}
     }
   ]).exec((err,data) => {
        if (err) {console.log(err)}
              res.json(data)
        });
});

【讨论】:

    猜你喜欢
    • 2018-05-10
    • 2013-02-22
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    相关资源
    最近更新 更多