Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to sort paginated list by custom field? #8

Open
kulakowka opened this issue Dec 20, 2016 · 4 comments
Open

How to sort paginated list by custom field? #8

kulakowka opened this issue Dec 20, 2016 · 4 comments

Comments

@kulakowka
Copy link

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
Copy link
Owner

jonlil commented Dec 20, 2016

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
Copy link
Author

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
Copy link
Author

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

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

@benevid
Copy link

benevid commented Feb 13, 2020

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);
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants