Say I have 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 in database (based on timestamp
order).
I want to get 6, 7, 8, 9, 10 in sequentia
To achieve your requirement you can use aggregate query
MessageModel.aggregate([
{ $sort : { timestamp: -1} },
{ $limit : 5 },
{ $sort : { timestamp: 1} }
])
.exec();
You can use Array#reverse to efficiently reverse the order of the elements in your messages
array in place to put them back in ascending order:
MessageModel
.find()
.sort({ timestamp: -1 })
.limit(5)
.exec()
.then(messages => {
messages.reverse();
console.log(messages);
})
.catch(err => console.log(err));