<!-- This file was generated by @travetto/doc and should not be modified directly -->
<!-- Please modify https://github.com/travetto/travetto/tree/main/module/model-mongo/DOC.tsx and execute "npx trv doc" to rebuild -->
# MongoDB Model Support

## Mongo backing for the travetto model module.

**Install: @travetto/model-mongo**
```bash
npm install @travetto/model-mongo

# or

yarn add @travetto/model-mongo
```

This module provides an [mongodb](https://mongodb.com)-based implementation for the [Data Modeling Support](https://github.com/travetto/travetto/tree/main/module/model#readme "Datastore abstraction for core operations.").  This source allows the [Data Modeling Support](https://github.com/travetto/travetto/tree/main/module/model#readme "Datastore abstraction for core operations.") module to read, write and query against [mongodb](https://mongodb.com).. Given the dynamic nature of [mongodb](https://mongodb.com), during development when models are modified, nothing needs to be done to adapt to the latest schema. 

Supported features:
   *  [CRUD](https://github.com/travetto/travetto/tree/main/module/model/src/types/crud.ts#L11)
   *  [Expiry](https://github.com/travetto/travetto/tree/main/module/model/src/types/expiry.ts#L10)
   *  [Bulk](https://github.com/travetto/travetto/tree/main/module/model/src/types/bulk.ts#L64)
   *  [Indexed](https://github.com/travetto/travetto/tree/main/module/model/src/types/indexed.ts#L11)
   *  [Blob](https://github.com/travetto/travetto/tree/main/module/model/src/types/blob.ts#L8)
   *  [Query Crud](https://github.com/travetto/travetto/tree/main/module/model-query/src/types/crud.ts#L11)
   *  [Facet](https://github.com/travetto/travetto/tree/main/module/model-query/src/types/facet.ts#L14)
   *  [Query](https://github.com/travetto/travetto/tree/main/module/model-query/src/types/query.ts#L10)
   *  [Suggest](https://github.com/travetto/travetto/tree/main/module/model-query/src/types/suggest.ts#L12)

Out of the box, by installing the module, everything should be wired up by default.If you need to customize any aspect of the source or config, you can override and register it with the [Dependency Injection](https://github.com/travetto/travetto/tree/main/module/di#readme "Dependency registration/management and injection support.") module.

**Code: Wiring up a custom Model Source**
```typescript
import { InjectableFactory } from '@travetto/di';
import { MongoModelService, type MongoModelConfig } from '@travetto/model-mongo';

export class Init {
  @InjectableFactory({
    primary: true
  })
  static getModelSource(config: MongoModelConfig) {
    return new MongoModelService(config);
  }
}
```

where the [MongoModelConfig](https://github.com/travetto/travetto/tree/main/module/model-mongo/src/config.ts#L10) is defined by:

**Code: Structure of MongoModelConfig**
```typescript
@Config('model.mongo')
export class MongoModelConfig {
  /**
   * Hosts
   */
  hosts?: string[];
  /**
   * Collection prefix
   */
  namespace?: string;
  /**
   * Username
   */
  username?: string;
  /**
   * Password
   */
  password?: string;
  /**
   * Server port
   */
  port?: number;
  /**
   * Direct mongo connection options, these do not go on the connection string
   */
  connectionOptions: mongo.MongoClientOptions = {};
  /**
   * Is using the SRV DNS record configuration
   */
  srvRecord?: boolean;
  /**
   * Mongo client options
   */
  options: mongo.MongoClientOptions = {};
  /**
   * Allow storage modification at runtime
   */
  modifyStorage?: boolean;
  /**
   * Frequency of culling for cullable content
   */
  cullRate?: number | TimeSpan;
  /**
   * Connection string
   */
  connectionString?: string;
  /**
   * Should we store the _id as a string in the id field
   */
  storeId?: boolean;

  /**
   * Load all the ssl certs as needed
   */
  async postConstruct(): Promise<void> {
    const resolve = (file: string): Promise<string> => RuntimeResources.resolve(file).catch(() => file);

    if (this.connectionString) {
      const details = new URL(this.connectionString);
      this.hosts ??= details.hostname.split(',').filter(host => !!host);
      this.srvRecord ??= details.protocol === 'mongodb+srv:';
      this.namespace ??= details.pathname.replace('/', '');
      Object.assign(this.options, Object.fromEntries(details.searchParams.entries()));
      this.port ??= +details.port;
      this.username ??= details.username;
      this.password ??= details.password;
    }

    // Defaults
    if (!this.namespace) {
      this.namespace = 'app';
    }
    if (!this.port || Number.isNaN(this.port)) {
      this.port = 27017;
    }
    if (!this.hosts || !this.hosts.length) {
      this.hosts = ['localhost'];
    }

    const options = this.options;
    if (options.ssl) {
      if (options.cert) {
        options.cert = await Promise.all([options.cert].flat(2).map(data => Buffer.isBuffer(data) ? data : resolve(data)));
      }
      if (options.tlsCertificateKeyFile) {
        options.tlsCertificateKeyFile = await resolve(options.tlsCertificateKeyFile);
      }
      if (options.tlsCAFile) {
        options.tlsCAFile = await resolve(options.tlsCAFile);
      }
      if (options.tlsCRLFile) {
        options.tlsCRLFile = await resolve(options.tlsCRLFile);
      }
    }

    if (!Runtime.production) {
      options.waitQueueTimeoutMS = 0;
      options.serverSelectionTimeoutMS = TimeUtil.asMillis(1, 's');
    }
  }

  /**
   * Build connection URLs
   */
  get url(): string {
    const hosts = this.hosts!
      .map(host => (this.srvRecord || host.includes(':')) ? host : `${host}:${this.port ?? 27017}`)
      .join(',');
    const optionString = new URLSearchParams(Object.entries(this.options)).toString();
    let creds = '';
    if (this.username) {
      creds = `${[this.username, this.password].filter(part => !!part).join(':')}@`;
    }
    const url = `mongodb${this.srvRecord ? '+srv' : ''}://${creds}${hosts}/${this.namespace}?${optionString}`;
    return url;
  }
}
```

Additionally, you can see that the class is registered with the [@Config](https://github.com/travetto/travetto/tree/main/module/config/src/decorator.ts#L13) annotation, and so these values can be overridden using the standard [Configuration](https://github.com/travetto/travetto/tree/main/module/config#readme "Configuration support") resolution paths.The SSL file options in `clientOptions` will automatically be resolved to files when given a path.  This path can be a resource path (will attempt to lookup using [RuntimeResources](https://github.com/travetto/travetto/tree/main/module/runtime/src/resources.ts#L8)) or just a standard file path.
