# Ottoman Class

# Defining an Ottoman's instance:

import { Ottoman } from "./ottoman";

const ottoman = new Ottoman();

Ottoman's instances are the backbone of Ottoman.js. They are the entry point to use the ODM in your app.

# Ottoman constructor options

Ottoman allows you to modify some settings, which could be useful for database modeling or migration, you can for example change the metadata key to define the model in documents.

import { Ottoman } from "./ottoman";

const ottoman = new Ottoman({
    modelKey: 'type',

The modelKey default value is set to _type, but maybe you want to change it to type as it's described in the example above.

The available configurations are:

interface OttomanConfig {
  collectionName?: string;
  scopeName?: string;
  idKey?: string;
  modelKey?: string;
  populateMaxDeep?: number;
  searchConsistency?: SearchConsistency;
  maxExpiry?: number;
  keyGenerator?: (params: { metadata: ModelMetadata }) => string;
  keyGeneratorDelimiter?: string;
  • collectionName: store value to use for each Model if it doesn't provide any. The default value will be the Model's name.
  • scopeName: store value to use for each Model if it doesn't provide any. The default value is _default
  • idKey: it's the value of the key to save your id. The default value is set to id
  • modelKey: define the key to store the model name into the document. The default value is _type
  • populateMaxDeep: set default value for population. Default value is 1.
  • searchConsistency: define default Search Consistency Strategy. The default value is SearchConsistency.NONE
  • maxExpiry: value used to create a collection for this instance. The default value is 300000.
  • keyGenerator: function to generate the key to store documents.
  • keyGeneratorDelimiter: string value used to build the document key. The default value is ::.

The default implementation for keyGenerator function is:

KEY_GENERATOR = ({ metadata }) => `${metadata.modelName}`;

keyGenerator can be overridden for each Model if you want, check this in model options

keyGeneratorDelimiter have 2 restrictions:

  1. Only support up to 2 characters
  2. The available characters are ~!#$%&*_\-:<>?.


If the value provided to keyGeneratorDelimiter is invalid Ottoman will throw a BadKeyGeneratorDelimiterError exception.

Some examples of keyGeneratorDelimiter:

  • :: (Default delimiter)
  • &
  • &?
  • _
  • ##

keyGeneratorDelimiter can be overridden for each Model if you want, check this in model options

# Connections

All your Models will be created via a connection and map to a Collection.

# Create a connection

You can connect to Couchbase Server with the connect() method.

import { Ottoman } from 'ottoman';

const ottoman = new Ottoman();

This is the minimum needed to connect to the travel-sample bucket. If the connection fails on your machine, try using instead of localhost.

# Connection String Anatomy

Connection Anatomy

# Connection options

connect function also support a javascript object as parameter.

import { Ottoman } from 'ottoman';

const ottoman = new Ottoman();
    connectionString: 'couchbase://localhost',
    bucketName: 'travel-sample',
    username: 'admin',
    password: 'password'

The available connections options are:

interface ConnectOptions {
  connectionString: string;
  username: string;
  password: string;
  bucketName: string;
  authenticator?: CertificateAuthenticator;
  trustStorePath?: string;
  transcoder?: unknown;
  logFunc?: unknown;

transcoder: Transcoder provides an interface for performing custom transcoding of document contents being retrieved and stored to the cluster. More details here (opens new window). logFunc: it's a callback function that receive the entry (opens new window) variable as paramater.

# Using the default ottoman instance functions

import { connect, model } from 'ottoman';
// connecting to server

// Now you can use the model function to create Models in the default instance.
const User = model('User', { name: String });


Notice we start using Ottoman without creating any instance, it's possible by using the connect function. connect function will create a default ottoman instance with default options if there's not an ottoman default instance created yet.

IMPORTANT: This will be the recommended way to use Ottoman if your app uses only 1 instance. This way ottoman will save for you the Ottoman instance to work in any place of your code.

Example model instead of ottoman.model. Also there are start, close, connect, getDefaultInstance' functions are available for Ottoman default instance.

# Certificate Authentication

Couchbase Server supports the use of X.509 certificates to authenticate clients (only available in the Enterprise Edition, not the Community Edition). This allows authenticated users to access specific resources by means of the data service, in Couchbase Server 5.1 and up, and all other services in more recent releases of Couchbase Data Platform.

The process relies on a certificate authority, for the issuing of certificates that validate identities. A certificate includes information such as the name of the entity it identifies, an expiration date, the name of the authority that issued the certificate, and the digital signature of the authority. A client attempting to access Couchbase Server can present a certificate to the server, allowing the server to check the validity of the certificate. If the certificate is valid, the user under whose identity the client is running, and the roles assigned that user, are verified. If the assigned roles are appropriate for the level of access requested to the specified resource, access is granted.

For a more detailed conceptual description of using certificates, see Certificates (opens new window).

# Authenticating Ottoman by Certificate

For sample procedures whereby certificates can be generated and deployed, see Manage Certificates (opens new window). The rest of this document assumes that the processes there, or something similar, have been followed. That is, a cluster certificate has been created and installed on the server, a client certificate has been created, and it is stored in a JVM keystore along with the cluster’s certificate.

import { Ottoman, CertificateAuthenticator } from 'ottoman';
const ottoman = new Ottoman();

  connectionString: 'couchbase://localhost',
  bucketName: 'travel-sample',
  authenticator: new CertificateAuthenticator(
  trustStorePath: "/path/to/ca/certificates.pem",

# Multiple ottoman instances

import { Ottoman } from 'ottoman';
const ottoman1 = new Ottoman();

const ottoman2 = new Ottoman();

// After connect you can create an explicitly Model from a given instance

//Creating UserModel from ottoman1
const UserModel = ottoman1.model('User', { name: String });

//Creating CatModel from ottoman2
const CatModel = ottoman2.model('Cat', { age: Number });

# Default ottoman instance

import { Ottoman, getDefaultInstance } from 'ottoman';
const ottoman1 = new Ottoman();
const ottoman2 = new Ottoman();

// Getting default instance
const defaultInstance = getDefaultInstance();
// defaultInstance = ottoman1;

The first ottoman instance created will be set as the default instance and could be accessed anywhere in your code by calling getDefaultInstance function.

# Closing connections

import { Ottoman, getDefaultInstance } from 'ottoman';
const ottoman1 = new Ottoman();

// Closing connection1

// Or just call the `close` function to close the default ottoman instance connection. In this case, the `ottoman1` connection will be closed.


Always remember to close your connections.

# Not using scopes/collections

If you don't want to use the scopes/collection approach set the ottoman instances this way:

import { Ottoman } from "./ottoman";

const ottoman = new Ottoman({collectionName: '_default'});

This way Ottoman will store all your data in a bucket.

# Bootstrapping

Ottoman class will provide 3 main methods in order to bootstrap the app:

  • ensureCollections will attempt to create collections and scopes for each model.
  • ensureIndexes will attempt to create all indexes defined in the schema definition.
  • start method is just a shortcut to run ensureCollections and ensureIndexes. Notice: It's not required to execute the start method to Ottoman work.

# Setting environment variables

Ottoman provide a set function to help you define environment variables. The next example will show how to set debug mode:

import { set } from 'ottoman';

// Setting Ottoman in debuggin mode
set('DEBUG', true);

Remember: You must define your environment variables at the very beginning.

# Helper functions

Ottoman provides some helpers functions:

# Next Up

Great job! Now we're connected, let's take a look at Schemas.