Options
All
  • Public
  • Public/Protected
  • All
Menu

Class QueryService<TDocument, TModel>

description

Abstraction layer for queries setup using the Mongo service. This class contains methods to validate, process and format database queries.

Native field values will be casted to their Typescript equivalent depending on the field value in Mongo, i.e. "true" becomes true.

Also, arrays are always passed to the $in routine, currently no other operations are possible with array and objects.

Note that you must pass a document class to the generic TDocument template of this class, e.g. QueryService.

example

Inject and use the QueryService in another class

 import { QueryService } from "./QueryService";

@Injectable()
export class ExampleService {
// inject QueryService
constructor(
@InjectModel(Example.name) private readonly model: ExampleModel,
private readonly queryService: QueryService<ExampleDocument, ExampleModel>,
) {}

// example usage
async findOne(query: ExampleQuery): Promise<ExampleDocument> {
return await this.queryService.findOne(query, this.model);
}
}
todo

add handler abstraction logic

todo

Method typecastField does not permit simple arithmetical operations like <><==> on numbers.

todo

Method typecastField is most likely incompatible with complex class objects, must be handled.

todo

Method typecastField mixes functionalities by defining the $in routines as a type-cast result.

since

v0.1.0

Type Parameters

  • TDocument extends Documentable

  • TModel extends Model<TDocument, {}, {}, {}> = Model<TDocument>

Hierarchy

  • QueryService

Index

Constructors

  • new QueryService<TDocument, TModel>(): QueryService<TDocument, TModel>
  • Type Parameters

    • TDocument extends Documentable<TDocument>

    • TModel extends Model<TDocument, {}, {}, {}, any, TModel> = Model<TDocument, {}, {}, {}, any>

    Returns QueryService<TDocument, TModel>

Methods

  • aggregate(query: PipelineStage[], model: TModel): Promise<Aggregate<TModel[]>>
  • This method performs an aggregate query and returns a mongo aggregate result which consists of a collection of the provided model's items.

    This method also executes the search query using the Mongo service connected to handle {@param model}.

    access

    public

    Parameters

    • query: PipelineStage[]
    • model: TModel

    Returns Promise<Aggregate<TModel[]>>

  • count(query: Queryable<TDocument>, model: TModel): Promise<number>
  • This method executes a count query using the {@link model} argument.

    Caution: Count queries require a considerable amount of RAM to execute. It is preferred to use pro-active statistics with collections that contain one document with a counter.

    access

    public

    async

    Parameters

    Returns Promise<number>

    The number of matching documents.

  • This method updates exactly one document in a collection. The query is build using getQueryConfig and can thereby use any columns of the document.

    access

    public

    async

    Parameters

    • query: Queryable<TDocument>

      The query configuration with sort, order, pageNumber, pageSize.

    • model: TModel

      The model class instance used for the resulting document.

    • data: Record<string, any>

      The fields or data that has to be updated (will be added to $set: {}).

    • ops: MongoQueryOperations = {}

      The operations that must be run additionally (e.g. $inc: {}) (optional).

    Returns Promise<TDocument>

  • exists(query: Queryable<TDocument>, model: TModel): Promise<boolean>
  • Method to query the existence of a document in the collection mapped to {@link TModel}.

    This executes a lean mongoose query such that the properties of the returned document are reduced to only the "_id" field.

    access

    public

    async

    Parameters

    • query: Queryable<TDocument>

      The query configuration with sort, order, pageNumber, pageSize.

    • model: TModel

      The model class instance used for matching documents.

    Returns Promise<boolean>

    Whether a document exists which validates the passed query.

  • Create a generic search query that is compatible with Mongo. The returned {@link PaginatedResultDto} contains a data field and a pagination field to permit multiple queries to be sequenced.

    This method also executes the search query using the Mongo service connected to handle {@param model}.

    access

    public

    async

    Parameters

    • query: Queryable<TDocument>

      The query configuration with sort, order, pageNumber, pageSize.

    • model: TModel

      The model class instance used for resulting documents.

    Returns Promise<PaginatedResultDTO<TDocument>>

    The matching documents after execution of the query.

  • findOne(query: Queryable<TDocument>, model: TModel, stripDocument?: boolean): Promise<TDocument>
  • Find one TDocument instance in the database and use a query based on the Queryable class.

    access

    public

    async

    Parameters

    • query: Queryable<TDocument>

      The query configuration with sort, order, pageNumber, pageSize.

    • model: TModel

      The model class instance used for the resulting document.

    • stripDocument: boolean = false

      Determines whether the query should be lean (strip out document properties).

    Returns Promise<TDocument>

    The resulting document.

  • Create a generic search query that is compatible with Mongo. The returned {@link PaginatedResultDto} contains a data field and a pagination field to permit multiple queries to be sequenced.

    This method also executes the search query using the Mongo service connected to handle {@param model}.

    access

    public

    async

    Parameters

    • query: Queryable<TDocument>

      The query configuration with sort, order, pageNumber, pageSize.

    • model: TModel

      The model class instance used for resulting documents.

    • ops: MongoQueryOperations = undefined

    Returns Promise<PaginatedResultDTO<TDocument>>

    The matching documents after execution of the query.

  • Format the search query parameters to a Mongo compatible aggregate search query. The resulting object can be used to configure an executable Mongo aggregation or query.

    Note that pagination parameters can be omitted with the following defaults being used: sort="_id", order="asc", pageNumber=1, pageSize=20.

    Note that this method takes three generics that must extend the Documentable class and must also contain a collectionName, e.g. in Account. Only the first of these generics is obligatory, others can be used when handling more complex union queries.

    access

    protected

    Type Parameters

    • T2ndDocument extends Documentable<T2ndDocument> & { collectionName: string }

    • T3rdDocument extends Documentable<T3rdDocument> & { collectionName: string } = any

    • T4thDocument extends Documentable<T4thDocument> & { collectionName: string } = any

    Parameters

    • query: Queryable<TDocument>

      The query configuration with sort, order, pageNumber, pageSize.

    • Optional unionWith: Map<string, Queryable<T2ndDocument | T3rdDocument | T4thDocument>>

      (Optional) This parameter should contain a map of Queryable objects - defaults to empty union specification (no union).

    • Optional metadata: MongoRoutineCount[]

      (Optional) This parameter should contain one or more $count pipeline stage(s) - defaults to empty metadata.

    Returns MongoQueryPipeline

    The resulting aggregate search query specification that is compatible with Mongo aggregate queries.

  • Format the search query parameters to a Mongo compatible documents search query. The resulting object can be used to configure an executable Mongo aggregation or query.

    Note that pagination parameters can be omitted with the following defaults being used: sort="_id", order="asc", pageNumber=1, pageSize=20.

    Note that the generic TQueryDocument should usually be an object that extends Documentable, this is the case for example with AccountDocument and it will also contain a collectionName as defined in Account.

    access

    protected

    Type Parameters

    Parameters

    • query: Queryable<TQueryDocument>

      The query configuration with sort, order, pageNumber, pageSize.

    Returns SearchQuery

    The configured SearchQuery with pagination parameters and sanitized Mongo query.

  • This method sanitizes a search query and returns a mongo compatible query that can be executed and uses the correct types for its conditions (and field values).

    This method can be used whenever data has been read from Mongo and still has string typed values. Note that this routine is not compatible with deep objects and may corrupt typings of complex class instances.

    access

    protected

    Parameters

    Returns MongoQueryConditions

    The sanitized search query, can be passed in mongoose $match.

  • This method type-casts individual query values to primitive types and creates routines for specific primitives like number or array.

    Following rules apply:

    1. If it's a boolean value ('true', 'false') convert it to boolean.
    2. If it's a number, returns { $in: [+value, value] } // both string and numeric values.
    3. If it's an array, loop through all items and check each one with step 1, 2 and 4
    4. If it's not any of the above types, it's a string. Returns original value.

      Note that objects or complex class instances cannot currently be type-cast using this method.
    access

    protected

    Parameters

    • value: any

      A field value that needs to be type-casted to a primitive or using a routine.

    Returns MongoQueryConditionValue

    A type-cast representation of the passed value or a Mongo routine configuration.

  • union<T2ndDocument, T3rdDocument, T4thDocument>(query: Queryable<TDocument>, model: TModel, unionWith: Map<string, Queryable<T2ndDocument | T3rdDocument | T4thDocument>>, metadata?: MongoRoutineCount[]): Promise<PaginatedResultDTO<TDocument & T2ndDocument & T3rdDocument & T4thDocument>>
  • Create a generic union search query that is compatible with Mongo. The returned {@link PaginatedResultDto} contains a data field and a pagination field to permit multiple queries to be sequenced.

    This method also executes the search query using the Mongo service connected to handle {@param model}.

    This method is different find in that it permits to execute a union query, effectively combining multiple collections in the result set.

    Note that this method takes three generics that must extend the Documentable class and must also contain a collectionName, e.g. in Account. Only the first of these generics is obligatory, others can be used when handling more complex union queries and by default may be omitted.

    access

    public

    async

    Type Parameters

    • T2ndDocument extends Documentable<T2ndDocument> & { collectionName: string }

    • T3rdDocument extends Documentable<T3rdDocument> & { collectionName: string } = any

    • T4thDocument extends Documentable<T4thDocument> & { collectionName: string } = any

    Parameters

    • query: Queryable<TDocument>

      The query configuration with sort, order, pageNumber, pageSize.

    • model: TModel

      The model class instance used for the resulting document.

    • unionWith: Map<string, Queryable<T2ndDocument | T3rdDocument | T4thDocument>>

      (Optional) This parameter should contain a map of Queryable objects - defaults to empty union specification (no union).

    • Optional metadata: MongoRoutineCount[]

      (Optional) This parameter should contain one or more $count pipeline stage(s) - defaults to empty metadata.

    Returns Promise<PaginatedResultDTO<TDocument & T2ndDocument & T3rdDocument & T4thDocument>>

    The resulting aggregate search query specification that is compatible with Mongo aggregate queries.

  • updateBatch(model: TModel, documents: TDocument[]): Promise<number>
  • Method to update a batch of documents in one collection. The query built here uses a document's _id field value and updates all fields present in the TDocument generic class.

    Note that the Documentable concern is used as a requirement of TDocument to make sure that the _id field is indeed present and populated.

    Note also that this method automatically sets the value of a field updatedAt to the time of execution of the query.

    todo

    Currently the $set parameters use new Date(), probably a mongo/mongoose routine for "now" is more adequate.

    access

    public

    async

    Parameters

    • model: TModel

      The model class instance used for the resulting document.

    • documents: TDocument[]

      The list of matching documents that must be updated with this batch operation.

    Returns Promise<number>

    The number of documents affected by the update queries.

Generated using TypeDoc