Keeping the First Results
Part of the Databases with MongoDB section of Coddy's Node.js journey. Lesson 12 of 29.
A page showing the two newest books needs only the first two results. A cursor has a limit method for this. The limit is a number of documents, not a field value.
await books.find().sort({year: 1}).limit(1).toArray();
// [Emma], the oldest bookOn a find cursor, MongoDB sorts before limiting, whichever order you chain the calls. Write sort first so the code reads in that order. An array is still returned when the limit is one. If fewer documents match than the limit, the database returns the available documents. No empty placeholders are added.
A query value is text: Number(input.page) || 1 uses its number, or 1 when it is missing. This practice accepts positive whole numbers.
Challenge
EasyKeep the supplied newest-first sort. Limit the results using input.n from the query string; use 2 when it is absent. Return the documents unchanged.
Try Run: GET /result?n=2 returns Kindred then Dune. With ?n=1, only Kindred remains. With no n, the default is two results. Inputs are positive whole numbers.
Try it yourself
export async function exercise(books, input) {
return await books.find().sort({ year: -1 }).toArray();
}
All lessons in Databases with MongoDB
Practice on your own: Express playground