Mongoose query pagination example

Project: bookmarks.dev - File: personal-bookmarks-search.service.js

Use the mongo cursor skip method with offset in combination with the limit method:

let getPersonalBookmarksForSearchFilter = async function (filter, pageNumber, nPerPage) {

  let bookmarks = await Bookmark.find(
    filter,
    {
      score: {$meta: "textScore"}
    }
  )
    .sort({score: {$meta: "textScore"}})
    .skip(pageNumber > 0 ? ((pageNumber - 1) * nPerPage) : 0)
    .limit(nPerPage)
    .lean()
    .exec();

  return bookmarks;
}

Reference - https://docs.mongodb.com/manual/reference/method/cursor.skip/


Shared with from Bookmarks.dev. Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Subscribe to our newsletter for more code resources and news

Adrian Matei

Adrian Matei
Life force expressing itself as a coding capable human being

Mongo create full text index example

Code snippets showing how to create a mongo create full text index and how to search for results with its help. Continue reading

Mongo full text search example

Published on February 07, 2021