Skip to content

@iamcalegari/mongoat

Enumerations

EnumerationDescription
CUSTOM_VALIDATION-
METHODS-

Classes

ClassDescription
Database-
Model-
MongoatConnectionErrorErro de conexão: Database não conectada, dbName ausente, sessão de transação indisponível.
MongoatDriverErrorWrap 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).
MongoatErrorBase error class for all errors raised by Mongoat itself (config conflicts, missing connection, missing dbName, etc.).
MongoatValidationErrorErro 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

InterfaceDescription
CreateModelProps-
DatabaseConfig-
DefaultProperties-
HookConfigDeclarative per-method hook configuration accepted by CreateModelProps.hooks.
HookContextMapctx 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.
MigrationContextThe object passed into a migration's up/down function.
MigrationModuleThe 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-
MongoatMigrationsConfigThe 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.
PluginContextThe 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).
PluginObjectA 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).
PostHookEntryPost-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.
SanitizeFilterOptionsOpções de sanitizeFilter.

Type Aliases

Type AliasDescription
CreateIndexProps-
DocumentDefaults-
HookFnA 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-
OnHookErrorCallback 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.
PluginA 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.
PluginSetupA 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.
SchemaClassConstructor type of a schema class decorated with @Schema.
SchemaWithDefaults-
ValidationQueryExpressions-

Functions

FunctionDescription
BsonTypeSugar over @Prop({ bsonType }).
defineConfigIdentity 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).
defineMigrationIdentity 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.
DescriptionSugar over @Prop({ description }).
EnumSugar over @Prop({ enum: values }).
getStatusRead-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.
MaxSugar over @Prop({ maximum }).
MaxLengthSugar over @Prop({ maxLength }).
MinSugar over @Prop({ minimum }).
MinLengthSugar over @Prop({ minLength }).
OptionalMarca 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.
PatternSugar over @Prop({ pattern }) — a regular expression string in the format MongoDB's $jsonSchema validator accepts.
PostSimé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.
PreRegistra 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
PropCanonical 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).
revertMigrationReverts a single applied migration via its down(ctx) export, removing its record from the control collection on success.
runMigrationsApplies 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).
runToSame 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.
sanitizeFilterSanitiza 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.
SchemaClass decorator that closes a decorated schema class. Runs AFTER all field decorators (a TC39 spec guarantee), so it sees the fully populated metadata.
toObjectIdConverts a given input into an ObjectId.