Mongoose query pagination example

Project: codever - 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 Codever. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Codever is open source on Github ⭐🙏

Subscribe to our newsletter for more code resources and news

Adrian Matei (aka adixchen)

Adrian Matei (aka adixchen)
Life force expressing itself as a coding capable human being

routerLink with query params in Angular html template

routerLink with query params in Angular html template code snippet Continue reading