7

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
Rahul Kumar
  • 5,120
  • 5
  • 33
  • 44

1 Answers1

14

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.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • this is working in parts, is returning what i want, but it is an object, I need to send for my views in a way that I can print in the html without appear '[object Object]' –  Jan 14 '15 at 16:18
  • @SuchMuchFunny It works. An array of objects that will JSON Stringify perfectly, just like any other result from the mongoose API. You are doing something wrong if you cannot make it work. It's pretty simple for the rest of us. – Neil Lunn Jan 14 '15 at 16:22
  • @SuchMuchFunny Nothing in MongoDB will do that. Your code needs to tranform the results or your "views" need to respect "key/value" principles. SQL Databases don't do that. Why would you expect something else of a different datastore? – Neil Lunn Jan 14 '15 at 16:28