1

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.