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

Array sortBy #29

Closed
kvlknctk opened this issue Sep 23, 2020 · 1 comment
Closed

Array sortBy #29

kvlknctk opened this issue Sep 23, 2020 · 1 comment

Comments

@kvlknctk
Copy link

Hi,

I want to use paginate with search and order params query. But this repo not supported this. I was tried multiple sortBy like this.

My url /endpoint?limit=5&page=1&sortBy[]=stars:desc&sortBy[]=price:asc
The positions of the ranking parameters affect the results. whichever applies first.

But I wonder is this best practice?

Just modified this area

schema.statics.paginate = async function(filter, options) {
    const sort = [];

    if (options.sortBy) {
      Object.entries(options.sortBy)
        .forEach(([key, value]) => {
          const parts = value.split(':');
          sort.push([parts[0], parts[1] === 'desc' ? -1 : 1]);
        });
    }

Whole code models/plugins.js

const paginate = (schema) => {
  /**
   * @typedef {Object} QueryResult
   * @property {Document[]} results - Results found
   * @property {number} page - Current page
   * @property {number} limit - Maximum number of results per page
   * @property {number} totalPages - Total number of pages
   * @property {number} totalResults - Total number of documents
   */
  /**
   * Query for documents with pagination
   * @param {Object} [filter] - Mongo filter
   * @param {Object} [options] - Query options
   * @param {string} [options.sortBy] - Sort option in the format: sortField:(desc|asc)
   * @param {number} [options.limit] - Maximum number of results per page (default = 10)
   * @param {number} [options.page] - Current page (default = 1)
   * @returns {Promise<QueryResult>}
   */
  schema.statics.paginate = async function(filter, options) {
    const sort = [];

    if (options.sortBy) {
      Object.entries(options.sortBy)
        .forEach(([key, value]) => {
          const parts = value.split(':');
          sort.push([parts[0], parts[1] === 'desc' ? -1 : 1]);
        });
    }

    const limit = options.limit && parseInt(options.limit, 10) > 0 ? parseInt(options.limit, 10) : 10;
    const page = options.page && parseInt(options.page, 10) > 0 ? parseInt(options.page, 10) : 1;
    const skip = (page - 1) * limit;

    const countPromise = this.countDocuments(filter).exec();
    const docsPromise = this.find(filter).populate('community').sort(sort).skip(skip).limit(limit).exec();

    return Promise.all([countPromise, docsPromise]).then((values) => {
      const [totalResults, results] = values;
      const totalPages = Math.ceil(totalResults / limit);
      const result = {
        results,
        page,
        limit,
        totalPages,
        totalResults
      };
      return Promise.resolve(result);
    });
  };
};

I took as an example : https://stackoverflow.com/a/13587343/4329812

Best regards.

@hagopj13
Copy link
Owner

@kvlknctk thanks for the suggestion. I have added the multiple criteria sorting feature to the paginate plugin. You can use it by specifying the sortBy field as, for instance, name:desc,role:asc

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

No branches or pull requests

2 participants