How to sort and limit the returned query results in mongoose

Project: codever - 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 Codever.land. 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