How do we write the aggregation queries in sails js other than sum and average.
Like we have Model.aggregate()
method in mongoose so how is the same thing done using sails-mongo
You have to use the available datastore manager in order to make a native query. Aggregate is not a waterline supported feature.
Documentation: https://sailsjs.com/documentation/reference/waterline-orm/datastores/manager
Here's an example:
const db = ModelName.getDatastore().manager;
const rawCollection = db.collection(tableName);
if (!rawCollection)
return res.serverError(
"Could not find tableName collection"
);
return rawCollection
.aggregate(
[
{
$match: {
createdAt: {
$gte: from,
$lte: to,
},
},
},
{ $sort: { createdAt: -1 } },
{
$group: {
},
},
{ $limit: page * limit + limit },
{ $skip: page * limit },
],
{
cursor: {
batchSize: 100,
},
}
)
.toArray((err, result) => {
if (err) return res.serverError(err);
let results = {
items: result,
total: result.length,
};
return res.json(results);
});
Change ModelName
and tableName
to be what you need.