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('index', {
        data: results

This works.

If i use

MyModel.find().sort('brand').skip((page-1)*15).limit(15).exec(function(err, results) {
    res.render('index', {
        data: results

This is also working, but how use both?

If i try, the error will show:

Error: skip cannot be used with distinct



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:

        { "$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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.