Skip to content

@iamcalegari/mongoat / Database

Class: Database ​

Defined in: src/database/index.ts:88

Constructors ​

Constructor ​

new Database(config?, client?, db?): Database

Defined in: src/database/index.ts:128

Create a new instance of the Database class.

Parameters ​

config? ​

DatabaseConfig = {}

An object with the configuration of the database.

client? ​

MongoClient

An instance of the MongoClient class.

db? ​

Db

An instance of the Db class.

The connection url is resolved from the MONGODB_URI env var first, then from config.uri. Credentials (MONGODB_USERNAME/MONGODB_PASSWORD env vars, then config.username/config.password) are optional: when both are present, the <username>/<password> placeholders in the uri are replaced with them; when absent, the uri is used as-is (e.g. a uri with embedded credentials, an Atlas SRV string, or a local instance without auth).

Only when neither MONGODB_URI nor config.uri is provided does the connection url fall back to the default 'mongodb://127.0.0.1:27017/'.

Beyond those four fields, DatabaseConfig extends MongoClientOptions: anything else set here is forwarded to MongoClient by connect(), overriding Mongoat's own defaults. That is where serverApi is opted into — see connect().

If the client and db parameters are not provided, the instances of the MongoClient and Db classes will be created automatically.

Returns ​

Database

Methods ​

[kCreateClientConnection]() ​

[kCreateClientConnection](options?): Promise<string>

Defined in: src/database/index.ts:582

Parameters ​

options? ​

MongoClientOptions

Returns ​

Promise<string>


[kGetUrlAndDbName]() ​

[kGetUrlAndDbName](): object

Defined in: src/database/index.ts:593

Returns ​

object

mongoDbName ​

mongoDbName: string

mongoUrl ​

mongoUrl: string


cleanCollections() ​

cleanCollections(): Promise<void>

Defined in: src/database/index.ts:458

Returns ​

Promise<void>


connect() ​

connect(): void | Promise<string>

Defined in: src/database/index.ts:199

Connect to the database. If the connection is already established, the method does nothing and returns nothing. If the connection is not established, the method returns a promise that resolves to a string containing the connection name.

Every driver option given to the constructor is forwarded to MongoClient here — DatabaseConfig extends MongoClientOptions, so the whole driver surface is configurable there — minus the four Mongoat-specific fields (uri, dbName, username, password), which Mongoat consumes itself. Precedence is explicit: Mongoat supplies DEFAULTS and the constructor's config overrides them, key by key. The only default is ignoreUndefined: true, which a caller can now switch off by passing ignoreUndefined: false.

No serverApi is configured. Declaring MongoDB's Stable API is the application's decision, never the ODM's, and it is expressed with the driver's own option:

ts
new Database({ uri, dbName, serverApi: { version: ServerApiVersion.v1 } });

Adding strict: true there makes the server reject every command outside Stable API v1 — $vectorSearch, createSearchIndex and listSearchIndexes among them, each failing with code: 323 (APIStrictError). Opt into it only when the application knows it uses nothing outside the API.

Returns ​

void | Promise<string>

A promise that resolves to a string containing the connection name, or nothing if the connection is already established.


disconnect() ​

disconnect(): Promise<void>

Defined in: src/database/index.ts:238

Disconnect from the database.

If the database connection is not established, the method does nothing.

Returns ​

Promise<void>

A promise that resolves to nothing.


getClient() ​

getClient(): MongoClient | undefined

Defined in: src/database/index.ts:415

Escape hatch honesto: devolve o MongoClient cru do driver oficial. Database nunca é envolvida em Proxy (só Model é, via registerModel()) — este getter já é "escape total" por natureza, sem nenhum gating a contornar. undefined antes de connect().

ATENÇÃO — bypass DELIBERADO: o MongoClient retornado é o objeto nativo do driver, fora de qualquer abstração do Mongoat. Ao chamar getClient() você saiu da zona segura do ODM — agora é o driver puro.

Returns ​

MongoClient | undefined

O MongoClient nativo, ou undefined se ainda não conectado.


getCollection() ​

getCollection<T>(collectionName): Collection<T> | undefined

Defined in: src/database/index.ts:397

Type Parameters ​

T ​

T extends Document

Parameters ​

collectionName ​

string

Returns ​

Collection<T> | undefined


getDb() ​

getDb(): Db | undefined

Defined in: src/database/index.ts:432

Escape hatch honesto: devolve o Db cru do driver oficial. Mesmo trade-off de getClient() — sem Proxy, sem gating, bypass total e deliberado. undefined antes de connect().

ATENÇÃO — bypass DELIBERADO: o Db retornado é o objeto nativo do driver. Ao chamar getDb() você saiu da zona segura do ODM — agora é o driver puro.

Returns ​

Db | undefined

O Db nativo, ou undefined se ainda não conectado.


getModel() ​

getModel(name): Model<Document> | undefined

Defined in: src/database/index.ts:268

Retrieves a model by its collection name.

Parameters ​

name ​

string

The name of the collection for which to retrieve the model.

Returns ​

Model<Document> | undefined

The model associated with the specified collection name, or undefined if it does not exist.


info() ​

info(): Promise<Document> | undefined

Defined in: src/database/index.ts:258

Returns information about the database.

The information returned is the result of the db.stats() method.

Returns ​

Promise<Document> | undefined

A promise that resolves to an object containing information about the database, or nothing if the connection is not established.


registerModel() ​

registerModel(model): Model<Document>

Defined in: src/database/index.ts:316

Registers a model in the database model map.

This method is used internally by the Model class constructor to register a model. If you want to register a model manually, you can use this method too — but a collectionName that is already occupied is no longer replaced unconditionally:

  • Passing back the SAME reference already stored for that collectionName is idempotent — it is returned as-is, no check runs.
  • A model carrying any hook (pre or post, of any origin — declared, decorated, or added by a plugin) throws MongoatValidationError with code: 'MODEL_CONFIG_CONFLICT'.
  • A model carrying a plugins list that diverges (by reference or order) from the one already registered also throws MongoatValidationError with code: 'MODEL_CONFIG_CONFLICT' — the same plugins comparison the Model constructor runs on re-registration, including for a plugin that registers only a static (no hook at all).
  • Otherwise, the candidate's config is compared field-by-field against the registered one (the same comparison the Model constructor runs on re-registration): identical → the existing instance is returned unchanged; divergent → throws MongoatValidationError with code: 'MODEL_CONFIG_CONFLICT', naming the divergent fields.

A free collectionName is unaffected — it still creates the Proxy, stores it, and returns it, exactly as before.

Parameters ​

model ​

Model<Document>

The model to be registered.

Returns ​

Model<Document>


setupCollection() ​

setupCollection(model): Promise<void>

Defined in: src/database/index.ts:444

Parameters ​

model ​

Model<Document>

Returns ​

Promise<void>


setupCollections() ​

setupCollections(): Promise<void>

Defined in: src/database/index.ts:436

Returns ​

Promise<void>


withTransaction() ​

withTransaction<T>(fn, options?): Promise<T | undefined>

Defined in: src/database/index.ts:481

Type Parameters ​

T ​

T = unknown

Parameters ​

fn ​

(session) => Promise<T> | undefined

options? ​

ClientSessionOptions

Returns ​

Promise<T | undefined>


loadModels() ​

static loadModels(modelsPath): Promise<void>

Defined in: src/database/index.ts:161

Parameters ​

modelsPath ​

string

Returns ​

Promise<void>