const preparedQuery = queryHelper({
    query: req.query,
    requiredQueryProperties: ['qrIdentifier'],
    additionalQuery: {
    project: '<projectId>',
    },
    additionalNotAllowedProperites: ['user'],
    additionalNotAllowedProjection: ['secret'],
});

queryHelper Function Usage

The queryHelper function processes the input query object to prepare a MongoDB ready query, ensuring it adheres to the required structure and constraints. It can handle various query features such asfiltering, pagination, grouping, sorting, populating related documents, and field projection. Internally, it utilizes the mongoose-query-parser package to parse the query object into a format suitable for Mongoose.

Arguments:

  • query (Required): The original query object from the request, which can include filtering conditions, pagination parameters (skip, limit), grouping parameter (groupedBy), and other MongoDB query parameters.
  • requiredQueryProperties (Optional): An array of strings specifying the properties that must be present in the query object.
  • additionalQuery (Optional): An object containing additional query parameters to be merged with the original query.
  • additionalNotAllowedProperties (Optional): An array of strings specifying properties that are not allowed in the query object.
  • additionalNotAllowedProjection (Optional): An array of strings specifying properties that should not be included in the projection.

Return:

The function returns an object with the following properties:
  • pagination: An object containing pagination parameters (skip and limit) if they were present in the original query.
  • sort: An object containing sorting instructions derived from the query.
  • condition: A MongoDB ready query object merged with any additional query parameters, prepared for filtering data.
  • populate: An object to specify the path for populating related documents, derived from the query.
  • projection: An object to specify which fields to include or exclude, derived from the query.
  • group: An object containing grouping parameters if groupedBy was specified in the original query.
Developers can adjust the global not allowed properties and not allowed projections within the queryHelper function as per the project requirements, or pass them as arguments if they are specific to certain queries. This utility function facilitates the handling of various query features in a structured and secure manner, making it easier to manage data retrieval operations in the application.

Example HTTP Requests:

// Example 1: Simple query with a filter and sort
GET /endpoint?name=John%20Doe&sort=-createdAt

// Example 2: Query with pagination
GET /endpoint?skip=10&limit=5
For more information on how to pass queries and the syntax, refer to the mongoose-query-parser documentation.