Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 786
Goran Avatar asked Jun 25 '14 14:06

Goran


People also ask

What is the use of $slice in MongoDB?

In MongoDB, the $slice operator decide the retrieval of a number of items of an array that a query returns. The $slice accepts a number including a negative number as an argument and returns the output.

What is skip in mongoose?

In Mongoose, the skip() method is used to specify the number of documents to skip. When a query is made and the query result is returned, the skip() method will skip the first n documents specified and return the remaining.


1 Answers

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) {
...
like image 50
dylants Avatar answered Nov 01 '22 17:11

dylants