In Mongoose, to retrieve the latest or oldest document records, you can achieve this by sorting and limiting the number of returned results.
For example, you have a model named Article that represents a collection of blog posts. Each document has a createdAt field, which is automatically set to the current date and time when a new document is created.
To retrieve the latest document record, you can use the .findOne() method combined with .sort() to sort by the createdAt field in descending order and limit the results to 1:
javascript// Retrieve the latest article record Article.findOne().sort('-createdAt').exec((err, latestDocument) => { if (err) { console.error(err); } else { console.log('Latest document record is:', latestDocument); } });
To retrieve the oldest document record, you can use the .sort() method to sort by the createdAt field in ascending order:
javascript// Retrieve the oldest article record Article.findOne().sort('createdAt').exec((err, oldestDocument) => { if (err) { console.error(err); } else { console.log('Oldest document record is:', oldestDocument); } });
This way, you can retrieve the latest or oldest document records as needed. If your documents do not have a createdAt field or other timestamp fields suitable for sorting, you need to add a timestamp field or use other fields for sorting.