I'm trying to do an aggregation query to the db for objects with a specific id, and sum it all up and as well give me an average.
My Scenario
I've a model that looks like this:
attributes: {
user: {
model: 'user',
required: true
},
rating: {
type: 'integer',
enum: [0, 1, 2, 3, 4, 5],
defaultsTo: 0,
required: true
},
inventory: {
model: 'subItem'
},
size: {
model: 'size',
required: true
},
isDeleted: {
type: 'boolean',
defaultsTo: false
}
}
Aggregating for the average rating like this:
const aggQuery = [
{
$match: {"size" : theRating.data[0].size, "isDeleted": false}
},
{
$group: {
_id: "$size",
total: { $sum: 1 },
average: { $avg: "$rating" }
}
}
]
My Function
module.exports = {
aggregateQuery: (model, aggregate) => {
return new Promise((resolve, reject) => {
model.native(function (err, collection) {
if (err) return reject(err);
collection.aggregate(aggregate, function (err, result) {
if (err) return reject(err);
return resolve(result);
})
})
})
}
}
Use Case I populate the db with 16 records while writing the test, but, after running the aggregate query, I get an empty array
NativeQueryService.aggregateQuery(Rating, aggQuery).then(result => {
console.log(result)
}).catch(err => {
console.log(err)
})
Any help on what I'm doing wrong would be appreciated. Thanks.
ObjectID@leonziyo