@iamcalegari/mongoat
Enumerations
| Enumeration | Description |
|---|---|
| CUSTOM_VALIDATION | - |
| METHODS | - |
Classes
| Class | Description |
|---|---|
| Database | - |
| Model | - |
| MongoatConnectionError | Erro de conexão: Database não conectada, dbName ausente, sessão de transação indisponível. |
| MongoatDriverError | Wrap sanitizado de um erro re-lançado pelo driver mongodb. .message é estável e nunca inclui stack trace/detalhes internos; o erro original do driver fica preservado em .cause para quem quiser inspecionar. Nunca construído a partir de JSON.stringify(err). |
| MongoatError | Base error class for all errors raised by Mongoat itself (config conflicts, missing connection, missing dbName, etc.). |
| MongoatValidationError | Erro de validação: schema/ObjectId inválido, filtro proibido ($where/operadores de execução de código), configuração de model divergente no registro, uso incorreto dos decorators de schema. |
Interfaces
| Interface | Description |
|---|---|
| CreateModelProps | - |
| DatabaseConfig | - |
| DefaultProperties | - |
| HookConfig | Declarative per-method hook configuration accepted by CreateModelProps.hooks. |
| HookContextMap | ctx shape per METHODS value — a lookup type keyed by the method literal so pre<M extends METHODS>(method: M, fn: (ctx: HookContextMap<ModelType>[M]) => ...) infers the right ctx from M. |
| MigrationContext | The object passed into a migration's up/down function. |
| MigrationModule | The shape a migration file must export. up is required; down is optional — a migration with no down export is irreversible by design (attempting to revert it is a fail-loud error, not a silent no-op). |
| ModelDbValidationProps | - |
| ModelSetup | - |
| ModelValidationSchema | - |
| MongoatMigrationsConfig | The authorable subset of MigrateConfig — the four migrations knobs a mongoat.config.{json,js,ts} file may set. Every field is optional and merges with CLI flags/env vars/defaults on a per-field basis. |
| PluginContext | The sealed surface a plugin's setup() receives. Reading schema/ allowedMethods never exposes the live model reference — both are disconnected copies, so mutating them has no effect on the model being built. The only way a plugin can affect the model is through the three registration methods below (pre/post/static). |
| PluginObject | A plugin expressed as an object with an explicit name — preferred when the identity needs to be stable independent of the setup function's own name (e.g. a setup function returned by a factory). |
| PostHookEntry | Post-hook registration entry. When fireAndForget is set (opt-in), the hook dispatch is truly non-awaited (does not delay the caller's return) and any rejection is routed to onHookError instead of propagating to the caller. |
| SanitizeFilterOptions | Opções de sanitizeFilter. |
Type Aliases
| Type Alias | Description |
|---|---|
| CreateIndexProps | - |
| DocumentDefaults | - |
| HookFn | A hook function invoked with an explicit ctx object. Sync or async; the return value convention differs between pre and post hooks: - pre hooks: return value is ignored (mutate ctx in place instead). - post hooks: undefined observes only; any other value transforms ctx.result (opt-in via return). |
| ObjectID | - |
| OnHookError | Callback invoked when a fireAndForget post-hook rejects. err is typed unknown — third-party hooks can throw anything, not necessarily a MongoatError/Error. Receives the SAME ctx the hook itself received (result/document/filter included) — the consumer of onHookError is responsible for not logging sensitive fields without redaction. |
| Plugin | A model plugin: either a bare setup function or an object carrying an explicit name alongside its setup. Parametrizable plugins are plain factory functions that return one of these two shapes — no extra API is needed to support options. |
| PluginSetup | A plugin expressed as a plain setup function. The function's own .name (or '<anonymous>' when unavailable) becomes the plugin's identity for deduplication and error messages. |
| SchemaClass | Constructor type of a schema class decorated with @Schema. |
| SchemaWithDefaults | - |
| ValidationQueryExpressions | - |
Functions
| Function | Description |
|---|---|
| BsonType | Sugar over @Prop({ bsonType }). |
| defineConfig | Identity helper for authoring a mongoat.config.{json,js,ts} file — takes the migrations config knobs and returns them unchanged, giving the author full type inference on MongoatMigrationsConfig without an explicit annotation on the exported object. A plain object literal works the same way without this helper — it exists purely for type-checking and autocomplete, never as a runtime requirement (a .json config has no code to call it from). |
| defineMigration | Identity helper for authoring a migration file — takes the up/down exports and returns them unchanged, giving the author full type inference on MigrationContext without an explicit annotation on the exported object. |
| Description | Sugar over @Prop({ description }). |
| Enum | Sugar over @Prop({ enum: values }). |
| getStatus | Read-only migration status report: one row per discovered migration file, paired with whatever applied-state is known about it. Unlike runMigrations/revertMigration, this NEVER throws on checksum drift — it only flags it (drifted: true) so a caller (e.g. the CLI's status command) can surface a warning without blocking. |
| Max | Sugar over @Prop({ maximum }). |
| MaxLength | Sugar over @Prop({ maxLength }). |
| Min | Sugar over @Prop({ minimum }). |
| MinLength | Sugar over @Prop({ minLength }). |
| Optional | Marca o campo como opcional — removido de required no Schema.compile (fiel ao rascunho do autor). Diferente dos demais açúcares (src/schema/sugars.ts), Optional NÃO agrega um fragmento em meta.properties — apenas registra o nome do campo em meta.optionalFields, filtrado de required no compile (não no momento em que o decorator roda). Isso torna o resultado idêntico independente da ordem textual entre @Optional() e @Prop/um açúcar no mesmo campo — ver o JSDoc de FieldMeta.optionalFields. |
| Pattern | Sugar over @Prop({ pattern }) — a regular expression string in the format MongoDB's $jsonSchema validator accepts. |
| Post | Simétrico a @Pre, mas SÓ no nível de CLASSE — post por campo não tem semântica clara (não há um "valor de campo" simétrico ao resultado de uma operação inteira). fn recebe o ctx completo, mesmo contrato de .post()/props.hooks; aplicar @Post a um campo lança MongoatValidationError. |
| Pre | Registra um hook pre no pipeline de hooks JÁ EXISTENTE do Model (nenhum novo dispatch) — aplicável em CLASSE e em CAMPO: - Nível de CLASSE: fn recebe o ctx COMPLETO, mesmo contrato de .pre()/props.hooks (`(ctx) => void |
| Prop | Canonical field decorator: declares the JSON Schema fragment for the decorated field. The fragment is written verbatim into the compiled schema — an omitted bsonType simply means "no type restriction" (pure JSON Schema semantics, no magic default). |
| revertMigration | Reverts a single applied migration via its down(ctx) export, removing its record from the control collection on success. |
| runMigrations | Applies every pending migration found in config.dir, in ascending lexicographic order, tracking applied state in config.collection (default _migrations). Idempotent — a migration whose version is already recorded as applied is never re-run. Before applying anything, re-verifies the checksum of every already-applied migration still on disk and refuses to proceed on any drift (MIGRATION_CHECKSUM_MISMATCH). |
| runTo | Same as runMigrations, but only applies pending migrations whose version is lexicographically <= version — lets a caller stop at a specific point in the migration history instead of always applying everything pending. Acquires and releases the same exclusive run lock as runMigrations, under the same ordering guarantees. |
| sanitizeFilter | Sanitiza um filtro de input não-confiável. OPT-IN — o dev chama explicitamente antes de montar/passar o filtro a um método do Model; nenhum método do Model chama isto automaticamente. |
| Schema | Class decorator that closes a decorated schema class. Runs AFTER all field decorators (a TC39 spec guarantee), so it sees the fully populated metadata. |
| toObjectId | Converts a given input into an ObjectId. |