I have implemented an aggregate function in mongoose to fetch some data, with a static implementation.
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)
})
})
I wanted to make it completely dynamic so I attempted the following:
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)
})
})
Upon debugging, it seems that match is not being passed in $match.
If I replace 'match' with a static variable, it works.
Here's the schema:
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);