# Models definitions

A database model is composed of two files: a definition file and a module.

The definition is composed of the following properties:

Property | Default | Example | Comment |
---: | --- | --- | --- |
*Database* |
`DATABASE` | `""` | `driver-state` | Database name for this model
[*Collection*](http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createCollection) |
`COLLECTION` | `""` | `events` | Collection name of the model
`COLLECTION_OPTIONS` | `{}` | `{ capped: true }` | Collection options applying to the collection: capped
[*Validator*]((https://docs.mongodb.com/v3.4/core/document-validation/)) |
`VALIDATOR_SCHEMA` | `{}` | `{ order_id: { $type: 'string' } }` | MongoDb validator schema definition
`VALIDATOR_OPTIONS` | `{}` | `{ validationLevel: 'strict' }` | MongoDb validator options
[*Indexes*]((http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createIndex)) |
`INDEXES` | `[]` | `[[{ correlation_id: 1 }, { unique: true }]]` | MongoDb validator schema definition

The definition file has the following structure:

```js
/**
 * CONFIGURATION
 */
const DATABASE = 'database';
const COLLECTION = 'collection';
const COLLECTION_OPTIONS = {};
const VALIDATOR_SCHEMA = {};
const VALIDATOR_OPTIONS = {
  validationLevel: 'off'
};

/**
 * @see http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#createIndex
 */
const INDEXES = [
  // [{ KEYS }, { OPTIONS }]
  // ie. [{ _id: 1 }, { name: '_id_' }]
];

module.exports = {
  DATABASE,
  COLLECTION,
  COLLECTION_OPTIONS,
  INDEXES,
  VALIDATOR_SCHEMA,
  VALIDATOR_OPTIONS
};

```

## Example

This example is taken from a model defined to store RabbitMQ messages into
a MongoDb collection:

```js
/**
 * CONFIGURATION
 */
const DATABASE = 'mole';

const COLLECTION = 'messages';
const COLLECTION_OPTIONS = {
  capped: true,
  max: 10000
};

const VALIDATOR_SCHEMA = {
  $and: [{
    exchange: { $type: 'string' },
    routing_key: { $type: 'string' },
    processed: { $type: 'bool' },
    date: { $type: 'date' },
    content: { $type: 'string' }
  }]
};

const VALIDATOR_OPTIONS = {
  validationAction: 'error',
  validationLevel: 'strict'
};

/**
 * @see http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#ensureIndex
 */
const INDEXES = [
  [{ date: 1 }, { expireAfterSeconds: 3600, background: true }], // Expire after 1 hour
  [{ processed: 1 }, { background: true }]
];

module.exports = {
  DATABASE,
  COLLECTION,
  COLLECTION_OPTIONS,
  INDEXES,
  VALIDATOR_SCHEMA
};

```
