jonlil / mongoose-paginate

mongoose-paginate
MIT License
26 stars 1 forks source link

How to sort paginated list by custom field? #8

Open kulakowka opened 7 years ago

kulakowka commented 7 years ago

Dear @jonlil.

Could you help me understand? I would like to get a list of articles sorted by number of comments.

Let my scheme looks like this:

var ArticleSchema = new mongoose.Schema({
  title: String,
  text: String,
  commentsCount: Number
})

Without mongoose-paginator query would look something like this:

Article
  .find()
  .sort('-commentsCount')
  .limit(10)
  .skip(5)
  .exec()

How can I do it with mongoose-paginator?

jonlil commented 7 years ago

Hi @kulakowka,

I believe you want todo something like this

Article.paginate({ sort: 'desc' }, 'commentsCount')
           .limit(10)
           .execPagination(function(err, results) {

          });

Please let me know if this works for you

kulakowka commented 7 years ago

Thank you @jonlil. I can do it tonight. At first glance, yes - that's what I need. I will inform you of the results.

kulakowka commented 7 years ago

Yes - that's what I need! Many thanks @jonlil.

I think it would be good to add this example in the documentation.

benevid commented 4 years ago

Hi, here is another example:

async getFromProfession(req, res) {
    const { page = 1 } = req.query;
    const jurymans = await Juryman.paginate(
      { profession: req.params.profession },
      {
        page,
        limit: 10,
        sort: {
          createdAt: -1 //Sort by Date Added DESC
        }
      }
    );
    return res.json(jurymans);
  }