Skip to content Skip to sidebar Skip to footer

How Use Mongoose Distinct, Skip And Limit Together

I need to use skip and limit for pagination, and the distinct for not return equal values. If i use MyModel.find().distinct('blaster', function(err, results) { res.render('inde

Solution 1:

You don't do that. .distinct() is a method that returns an "array", and therefore you cannot modify something that is not a "Cursor" with "cursor modifiers" like .limit() and .skip().

What you want is the .aggregate() method. Much more than just adding things up:

MyModel.aggregate(
    [
        { "$group": { "_id": "$blaster" } },
        { "$skip": ( page-1 ) * 15 },
        { "$limit": 15 }
    ],
    function(err,results) {
       // results skipped and limited in here
    }
);

The aggregation framework provides another way to achieve "distinct" results. But in a more flexible way. See the operators for $group, $skip and $limit.

Post a Comment for "How Use Mongoose Distinct, Skip And Limit Together"