Goran
Goran

Reputation: 1012

How to use .slice in mongoose

I got this in my app

...
Score.find({ match: {$in: ids}} )
     .sort([[score_sort, 'descending']])
     .slice([skip, limit])
     .exec(function(err, scores) {
    if (err || !scores) {
        throw err;
    } else {
        // do something cool
    }
});

But I get an error using the slice operation, the error is:

Error: slice() must be used after where() when called with these arguments

I have tried to replace .find with .where but I still get the same error. Anyone knows how to fix this?

Upvotes: 7

Views: 11047

Answers (2)

Goran
Goran

Reputation: 1012

...

Score.find({ match: {$in: ids}} )
     .sort([[score_sort, 'descending']])
     .skip(skip)
     .limit(limit)
     .exec(function(err, scores) {
    if (err || !scores) {
        throw err;
    } else {
        // do something cool
    }
});

Upvotes: 4

dylants
dylants

Reputation: 23340

slice() requires a path specified, which can be set either in an earlier where() call or within the slice() call itself. From the docs:

query.slice('comments', 5)
// or...
query.where('comments').slice(5)

Basically you need to state what you are slicing. It's not clear from your example, but imagine your Score model has an array of players -- you could use slice() to only return the first 5 players from each score via:

Score.find().slice('players', 5).exec(function(err, scores) {
...

Upvotes: 8

Related Questions