mongoloquent
    Preparing search index...

    Class Model<T>

    Base model class for all MongoDB models Extends QueryBuilder to provide query building capabilities

    Type Parameters

    • T

      Type of the model schema

    Hierarchy (View Summary)

    Indexable

    • [key: string]: any

      Dynamic property accessor for model attributes

    Index

    Constructors

    Properties

    $alias: string = ""

    Alias for relationship

    $changes: Partial<Record<keyof T, any>> = {}

    Changes made to the document

    $collection: string = "mongoloquent"

    Collection name

    $connection: string = ""

    MongoDB connection string

    $databaseName: string = ""

    Database name

    $deletedAt: string = "deletedAt"

    Field name for the deletedAt timestamp

    $id: null | string | ObjectId = null

    Document ID

    $isDeleted: string = "isDeleted"

    Field name for the isDeleted flag

    $limit: number = 0

    Number of documents to limit in query

    $lookups: Document[] = []

    Lookup stages for aggregation pipelines

    $options: IRelationOptions = {}

    Relationship options

    $original: Partial<T> = {}

    Original document data

    $useSoftDelete: boolean = false

    Flag to enable soft delete functionality

    $useTimestamps: boolean = true

    Flag to enable timestamps

    $collection: string = ""

    Collection name

    $connection: string = MONGOLOQUENT_DATABASE_URI

    Default MongoDB connection string

    $databaseName: string = MONGOLOQUENT_DATABASE_NAME

    Default database name

    $isDeleted: string = "isDeleted"

    Field name for the isDeleted flag

    $schema: any

    Schema definition for the document

    $timezone: string = TIMEZONE

    Field name for the timezone

    $useSoftDelete: boolean = false

    Flag to enable soft delete functionality

    $useTimestamps: boolean = true

    Flag to enable timestamps

    Methods

    • Defines a belongs-to relationship

      Type Parameters

      • M

        Type of the related model

      Parameters

      • model: new () => Model<M>

        Related model class

      • OptionalforeignKey: keyof T

        Foreign key on this model

      • OptionalownerKey: keyof M

        Owner key on related model

      Returns BelongsTo<T, M>

      BelongsTo relationship instance

    • Defines a belongs-to-many relationship

      Type Parameters

      • M

        Type of the related model

      • TM

        Type of the pivot model

      Parameters

      • model: new () => Model<M>

        Related model class

      • Optionalcollection: string

        Pivot collection name

      • OptionalforeignPivotKey: keyof TM

        Foreign key on pivot model for this model

      • OptionalrelatedPivotKey: keyof TM

        Foreign key on pivot model for related model

      • OptionalparentKey: keyof T = ...

        Primary key on this model

      • OptionalrelatedKey: keyof M = ...

        Primary key on related model

      Returns BelongsToMany<T, M, TM>

      BelongsToMany relationship instance

    • Alias for insertMany - creates multiple documents in the collection

      Parameters

      • docs: FormSchema<T>[]

        Array of documents to create

      • Optionaloptions: BulkWriteOptions

        MongoDB bulk write options

      Returns Promise<ObjectId[]>

      Array of created document IDs

    • Deletes documents by IDs (soft delete if enabled)

      Parameters

      • ...ids: (string | ObjectId | (string | ObjectId)[])[]

        IDs of documents to delete

      Returns Promise<number>

      Number of documents deleted or soft-deleted

    • Returns the first document matching the query as an enhanced instance

      Type Parameters

      • K extends string | number | symbol

        Keys of document type T

      Parameters

      • ...fields: (K | K[])[]

        Optional fields to select

      Returns Promise<null | Model<T> & T>

      First matching document or null if none found

    • Returns first matching document or creates a new one

      Parameters

      • filter: Partial<FormSchema<T>>

        Filter to find existing document

      • Optionaldoc: Partial<FormSchema<T>>

        Data to use for creation if no match is found

      Returns Promise<T>

      Existing or newly created document

    • Returns the first document matching the query or throws exception if none found

      Type Parameters

      • K extends string | number | symbol

        Keys of document type T

      Parameters

      • ...columns: (K | K[])[]

        Optional fields to select

      Returns Promise<Model<T> & T>

      First matching document

      If no document found

    • Alias for firstOrCreate - returns existing document or creates a new model instance

      Parameters

      • filter: Partial<FormSchema<T>>

        Filter to find existing document

      • Optionaldoc: Partial<FormSchema<T>>

        Data to use for the new instance if no match is found

      Returns Promise<T>

      Existing or newly created document

    • Permanently deletes soft-deleted documents by IDs

      Parameters

      • ...ids: (string | ObjectId | (string | ObjectId)[])[]

        IDs of documents to permanently delete

      Returns Promise<number>

      Number of documents permanently deleted

      If force deletion fails

    • Defines a has-many relationship

      Type Parameters

      • M

        Type of the related model

      Parameters

      • model: new () => Model<M>

        Related model class

      • OptionalforeignKey: keyof M

        Foreign key on related model

      • OptionallocalKey: keyof T

        Local key on this model

      Returns HasMany<T, M>

      HasMany relationship instance

    • Defines a has-many-through relationship

      Type Parameters

      • M

        Type of the related model

      • TM

        Type of the intermediate model

      Parameters

      • model: new () => Model<M>

        Related model class

      • throughModel: new () => Model<TM>

        Intermediate model class

      • OptionalforeignKey: keyof TM

        Foreign key on intermediate model

      • OptionalforeignKeyThrough: keyof M

        Foreign key on related model

      • localKey: keyof T = ...

        Local key on this model

      • localKeyThrough: keyof TM = ...

        Local key on intermediate model

      Returns HasManyThrough<T, M, TM>

      HasManyThrough relationship instance

    • Defines a has-one relationship

      Type Parameters

      • M

        Type of the related model

      Parameters

      • model: new () => Model<M>

        Related model class

      • OptionalforeignKey: keyof M

        Foreign key on related model

      • OptionallocalKey: keyof T

        Local key on this model

      Returns HasOne<T, M>

      HasOne relationship instance

    • Inserts multiple documents into the collection

      Parameters

      • docs: FormSchema<T>[]

        Array of documents to insert

      • Optionaloptions: BulkWriteOptions

        MongoDB bulk write options

      Returns Promise<ObjectId[]>

      Array of inserted document IDs

      If bulk insertion fails

    • Checks if all of the specified fields are unchanged

      Type Parameters

      • K extends string | number | symbol

        Keys of document type T

      Parameters

      • ...fields: (K | K[])[]

        Fields to check

      Returns boolean

      True if all fields are clean, false otherwise

    • Checks if any of the specified fields have been changed

      Type Parameters

      • K extends string | number | symbol

        Keys of document type T

      Parameters

      • ...fields: (K | K[])[]

        Fields to check

      Returns boolean

      True if any field is dirty, false otherwise

    • Defines a morphed-by-many relationship

      Type Parameters

      • M

        Type of the related model

      Parameters

      • model: new () => Model<M>

        Related model class

      • name: string

        Name of the polymorphic relation

      Returns MorphedByMany<T, M>

      MorphedByMany relationship instance

    • Defines a morph-many relationship

      Type Parameters

      • M

        Type of the related model

      Parameters

      • model: new () => Model<M>

        Related model class

      • name: string

        Name of the polymorphic relation

      Returns MorphMany<T, M>

      MorphMany relationship instance

    • Defines a morph-to relationship

      Type Parameters

      • M

        Type of the related model

      Parameters

      • model: new () => Model<M>

        Related model class

      • name: string

        Name of the polymorphic relation

      Returns MorphTo<T, M>

      MorphTo relationship instance

    • Defines a morph-to-many relationship

      Type Parameters

      • M

        Type of the related model

      Parameters

      • model: new () => Model<M>

        Related model class

      • name: string

        Name of the polymorphic relation

      Returns MorphToMany<T, M>

      MorphToMany relationship instance

    • Sets the order for the query results

      Type Parameters

      • K extends string | number | symbol

        Keys of document type T

      Parameters

      • column: K

        Column to order by

      • Optionaldirection: "asc" | "desc" = "asc"

        Sort direction (asc or desc)

      • OptionalcaseSensitive: boolean = false

        Whether sorting should be case sensitive

      Returns this

      Current query builder instance

    • Adds an OR where condition to the query

      Type Parameters

      • K extends string | number | symbol

        Keys of document type T

      Parameters

      • column: K

        Column name

      • operator: any

        Operator or value if comparing equality

      • Optionalvalue: any = null

        Value to compare against (optional if operator is the value)

      Returns QueryBuilder<T>

      Current query builder instance

    • Returns paginated results with metadata

      Parameters

      • Optionalpage: number = 1

        Page number (starting from 1)

      • Optionallimit: number = 15

        Number of items per page

      Returns Promise<IModelPaginate>

      Object containing data and pagination metadata

      If pagination fails

    • Updates a document in the collection based on the current query

      Parameters

      • doc: Partial<FormSchema<T>>

        Document fields to update

      • Optionaloptions: FindOneAndUpdateOptions = {}

        MongoDB findOneAndUpdate options

      Returns Promise<null | WithId<FormSchema<T>>>

      Updated document

      If update fails

    • Updates multiple documents in the collection matching the current query

      Parameters

      • doc: Partial<FormSchema<T>>

        Document fields to update

      • Optionaloptions: UpdateOptions

        MongoDB updateMany options

      Returns Promise<number>

      Number of documents modified

      If bulk update fails

    • Updates a document if it exists, otherwise creates it

      Parameters

      • filter: Partial<FormSchema<T>>

        Filter to find the document

      • Optionaldoc: Partial<FormSchema<T>>

        Document fields to update or insert

      Returns Promise<T | WithId<FormSchema<T>>>

      Updated or created document

    • Alias for updateOrCreate

      Parameters

      • filter: Partial<FormSchema<T>>

        Filter to find the document

      • Optionaldoc: Partial<FormSchema<T>>

        Document fields to update or insert

      Returns Promise<T | WithId<FormSchema<T>>>

      Updated or created document

    • Adds a where condition to the query

      Type Parameters

      • K extends string | number | symbol

        Keys of document type T

      Parameters

      • column: K

        Column name

      • operator: any

        Operator or value if comparing equality

      • Optionalvalue: any = null

        Value to compare against (optional if operator is the value)

      Returns QueryBuilder<T>

      Current query builder instance

    • Gets the average value for a column

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • column: keyof M["$schema"]

        Column to check

      Returns Promise<number>

      Average value

    • Creates a new document in the collection

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • doc: FormSchema<M["$schema"]>

        Document to create

      • Optionaloptions: InsertOneOptions

        MongoDB insert options

      Returns Promise<M["$schema"]>

      Created document

    • Creates multiple documents in the collection

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • doc: FormSchema<M["$schema"]>[]

        Documents to create

      • Optionaloptions: BulkWriteOptions

        MongoDB bulk write options

      Returns Promise<ObjectId[]>

      Created documents

    • Soft deletes documents by their IDs

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • ...ids: (string | ObjectId | (string | ObjectId)[])[]

        IDs of documents to delete

      Returns Promise<number>

      Result of the delete operation

    • Finds a document by its ID

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • id: string | ObjectId

        Document ID

      Returns Promise<InstanceType<M>>

      Retrieved document as model instance

    • Gets the first document matching the query

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • ...fields: (keyof M["$schema"] | (keyof M["$schema"])[])[]

        Fields to select

      Returns Promise<null | Model<M["$schema"]> & M["$schema"]>

      First matching document

    • Gets the first document matching the filter or creates it

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • filter: Partial<M["$schema"]>

        Filter to find the document

      • Optionaldoc: Partial<FormSchema<M["$schema"]>>

        Document to create if not found

      Returns Promise<M["$schema"]>

      Retrieved or created document

    • Gets the first document matching the filter or returns a new model instance

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • filter: Partial<M["$schema"]>

        Filter to find the document

      • Optionaldoc: Partial<FormSchema<M["$schema"]>>

        Document properties for the new instance

      Returns Promise<M["$schema"]>

      Retrieved document or new instance

    • Hard deletes documents by their IDs

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • ...ids: (string | ObjectId | (string | ObjectId)[])[]

        IDs of documents to delete

      Returns Promise<number>

      Result of the delete operation

    • Executes the query and returns the documents

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • ...fields: (keyof M["$schema"] | (keyof M["$schema"])[])[]

        Fields to select

      Returns Promise<Collection<M["$schema"]>>

      Retrieved documents

    • Inserts a new document into the collection

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • doc: FormSchema<M["$schema"]>

        Document to insert

      • Optionaloptions: InsertOneOptions

        MongoDB insert options

      Returns Promise<M["$schema"]>

      Inserted document

    • Inserts multiple documents into the collection

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • doc: FormSchema<M["$schema"]>[]

        Documents to insert

      • Optionaloptions: BulkWriteOptions

        MongoDB bulk write options

      Returns Promise<ObjectId[]>

      Inserted documents

    • Gets the maximum value for a column

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • column: keyof M["$schema"]

        Column to check

      Returns Promise<number>

      Maximum value

    • Gets the minimum value for a column

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • column: keyof M["$schema"]

        Column to check

      Returns Promise<number>

      Minimum value

    • Sets the order for the query results

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • column: keyof M["$schema"]

        Column to sort by

      • direction: "asc" | "desc" = "asc"

        Sort direction

      • caseSensitive: boolean = false

        Whether to use case sensitive sorting

      Returns Model<M["$schema"]>

      Query builder instance

    • Adds an OR where clause to the query

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • column: keyof M["$schema"]

        Column to filter on

      • operator: any

        Operator or value

      • Optionalvalue: any = null

        Value if operator is provided

      Returns QueryBuilder<M["$schema"]>

      Query builder instance

    • Adds an OR where between clause to the query

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • column: keyof M["$schema"]

        Column to filter on

      • value: [number, number?]

        Range values [min, max]

      Returns QueryBuilder<M["$schema"]>

      Query builder instance

    • Adds an OR where not in clause to the query

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • column: keyof M["$schema"]

        Column to filter on

      • value: any[]

        Array of values to exclude

      Returns QueryBuilder<M["$schema"]>

      Query builder instance

    • Gets paginated results from the query

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • page: number = 1

        Page number

      • Optionallimit: number = 15

        Documents per page

      Returns Promise<IModelPaginate>

      Paginated results and metadata

    • Gets values from specified fields as an array

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • ...fields: (keyof M["$schema"] | (keyof M["$schema"])[])[]

        Fields to retrieve values from

      Returns Promise<Collection<Pick<M["$schema"], keyof M["$schema"]>>>

      Array of field values

    • Gets the sum of values for a column

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • column: keyof M["$schema"]

        Column to sum

      Returns Promise<number>

      Sum of values

    • Updates a document or creates it if it doesn't exist

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • filter: Partial<FormSchema<M["$schema"]>>

        Filter to find document

      • Optionaldoc: Partial<FormSchema<M["$schema"]>>

        Document to update or create

      Returns Promise<M["$schema"] | WithId<FormSchema<M["$schema"]>>>

      Updated or created document

    • Updates a document or inserts it if it doesn't exist

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • filter: Partial<FormSchema<M["$schema"]>>

        Filter to find document

      • Optionaldoc: Partial<FormSchema<M["$schema"]>>

        Document to update or insert

      Returns Promise<M["$schema"] | WithId<FormSchema<M["$schema"]>>>

      Updated or inserted document

    • Adds a where clause to the query

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • column: keyof M["$schema"]

        Column to filter on

      • operator: any

        Operator or value

      • Optionalvalue: any = null

        Value if operator is provided

      Returns QueryBuilder<M["$schema"]>

      Query builder instance

    • Adds a where between clause to the query

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • column: keyof M["$schema"]

        Column to filter on

      • value: [number, number?]

        Range values [min, max]

      Returns QueryBuilder<M["$schema"]>

      Query builder instance

    • Eager loads a relation

      Type Parameters

      • M extends typeof Model

        Type of the model class

      Parameters

      • this: M
      • relation: string

        Relation name

      • Optionaloptions: IRelationOptions = {}

        Relation loading options

      Returns Model<M["$schema"]>

      Query builder instance