5

I am using express,mongoose,node.so i have checked this query regarding to skip and limit of documents.

   Model.find({},null,{limit:2,skip:20},function(err,data){
           //console.log(data)
      })
coder
  • 540
  • 1
  • 5
  • 17

3 Answers3

13

not sure but I think it's help full for you.

var perPage = 10
  , page = Math.max(0, req.param('page'))

Event.find()
    .select('name')
    .skip(perPage * page)
    .limit(perPage)
    .sort({
        name: 'asc'
    })
    .exec(function(err, events) {
        Event.count().exec(function(err, count) {
            res.render('events', {
                events: events,
                page: page,
                pages: count / perPage
            })
        })
    })

or see

How to paginate with Mongoose in Node.js?

Muho
  • 3,188
  • 23
  • 34
Neeraj Prajapati
  • 541
  • 5
  • 24
  • 1
    How would you get the results for page 1? Wouldn't that return the results for page 2 instead? – kawerewagaba Mar 08 '19 at 02:19
  • 3
    I think the best way is to `skip((pageNumber - 1) * limit)` which would skip `nothing (or 0) for page 1, limit for page 2, limit + limit for page 3, limit + limit + limit for page 4, limit * (n - 1) for page n` – kawerewagaba Mar 08 '19 at 02:24
  • 2
    Close... But as @ckwagaba said this skips first 10 all the time. Use (page - 1) * skip for the correct algo. – Brad Bird Jun 03 '19 at 01:22
9
var query = Model.find({}).skip(2).limit(5)
query.exec(callback);

write your code in callback

query.exec(function(err,data){
   //console.log(data)
});

You can also do some more query like this

Model
.where('field1').gte(25)
.where().in([])
.select('field1', 'field2', 'field13')
.skip(20)
.limit(10)
.asc('field1')
.exec(callback);

You can refer docs for more details

abdulbarik
  • 6,101
  • 5
  • 38
  • 59
3

Try this

Model.find({},null,{limit:2,skip:20}).then(function(data){
       //console.log(data)
  }).catch(next);