Home > Software engineering >  mongoose pagination with sort in not working properly
mongoose pagination with sort in not working properly

Time:08-17

I have a such function for pagination

async getMovies( pageNumber: number,limit: number = 20 ): Promise<MovieListResponse> {
const offset = (pageNumber - 1) * limit
const moviesCount = await this.movieModel.count()
const nextPage = pageNumber === Math.ceil(moviesCount / limit) ? null : pageNumber   1

const movies = await this.movieModel
  .find(
    { status: 'Released', release_date: { $lte: Date.now() } },
    {
      poster: 1,
      title: 1,
      id: 1,
    }
  )
  .skip(offset)
  .limit(limit)
  .sort({ release_date: 'desc' }) //Here is a problem

return {
  data: movies,
  nextPage,
 }
}

Without sort its working correctly, but if i add sort i will get some data from previous page

CodePudding user response:

This happens because Mongoose can't recognise the difference between identical values in multiple documents. By giving release_date, you may have some Movies documents with identical release_date values and Mongoose can't sort them correctly.

To fix this issue, just add _id in the sort function:

.sort({ release_date: 'desc', _id: 'desc' }) // or _id: -1

And now Mongoose can resolve the sort by their _id, when release_date are the same in multiple documents.

  • Related