How to sort and limit the returned query results in mongoose

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

Use the sort and limit methods. In the following example we receive the latest 30 (limit) created bookmarks (sort descending by createdAt date) :

let getLastCreatedBookmarks = async (userId) => {
  const bookmarks = await Bookmark.find({userId: userId})
    .sort({createdAt: -1}) // -1 for descending sort
    .limit(30);

  return bookmarks;
};

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


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

Mongoose query pagination example

Published on February 05, 2021