# Model
Models are fancy constructors compiled from Schema definitions. An instance of a model is called a document. Models are responsible for creating and reading documents from the underlying Couchbase database.
# Compiling your first model
When you call model() function on a schema, Ottoman compiles a model for you.
const schema = new Schema({ name: String, age: Number });
const User = model('User', schema);
WARNING
The model() function makes a copy of the schema. Make sure that you've added everything you want to the schema, including hooks, before calling model()!
# Model Options
You can pass a third argument to model() functions in order to setup your needs.
In the next example we will set the collectionName
to be users
.
const schema = new Schema({ name: String, age: Number });
const User = model('User', schema, { collectionName: 'users' });
Defining Collection Name
Models will be mapped to your Collections, if no Collection name option is provided then the Collection name will be equal to the Model name. There is an exception to this rule:
If you provide a
collectionName
option at Ottoman instance level then the Collection name will be equal to OttomancollectionName
option if it's not explicitly passed ascollectionName
in model options.import { Ottoman } from 'ottoman'; const ottoman = new Ottoman({ collectionName: '_default' }); const schema = new Schema({ name: String, age: Number }); // Collection name for model `Cat` will be `_default` const Cat = ottoman.model('Cat', schema); // Collection name for model `Dog` will be `dogs` const Dog = ottoman.model('Dog', schema, { collectionName: 'dogs' });
Therefore this is the way to get the Collection name for a Model: Collection Name = Model
collectionName
Options > OttomancollectionName
Options > Model name
The models options are:
interface ModelOptions {
collectionName?: string;
scopeName?: string;
idKey?: string;
modelKey?: string;
maxExpiry?: string;
keyGenerator?: (params: { metadata: ModelMetadata }) => string;
}
collectionName
: define the collection name to be use in the Couchbase Server. The default value will be the Model's name.scopeName
: define the scope where the collection will be placed. 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
maxExpiry
: value used to create a collection for this instance. The default value is300000
.keyGenerator
: function to generate the key to store documents.
If you don't provided a keyGenerator
implementation it will be inherited by Ottoman
instance options, check this in Ottoman options
# Model id
Ottoman will generate automatically your document's id
and will guarantee that each id
will be unique.
Each document's id
will be included on the document under a property called id
by default.
The id
property name can be modified using the ModelOptions.idKey
const schema = new Schema({ name: String, age: Number });
const User = model('User', schema, { collectionName: 'users', idKey: '__id' });
The above example will override the default id
with __id
, now for the User
's documents you can get the id
value from doc.__id.
TIP
You can also get the id
value by calling the doc._getId()
methods, regardless of the id
property name.
# Constructing Documents
An instance of a model is called a document. Creating and saving them to the database is easy.
const User = model('User', schema);
const user = new User({ name: 'Jane', age: 29 });
user.save();
// saved!
// or
User.create({ name: 'Jane', age: 29 });
// saved!
Note that no users will be created/removed until the connection that your model uses is open. Every model has an associated connection. When you use model(), your model will use the default Ottoman connection.
# Create Many
Also you can use createMany
static function to create multiples documents at once.
See the API docs for more detail.
User.createMany([{ name: 'John' }, { name: 'Jane' }]);
TIP
The response status will be SUCCESS as long as no error occurs, otherwise it will be FAILURE.
# Querying
Finding documents is easy with Ottoman, powered by the built-in Query Builder.
Documents can be retrieved using each models find
, findById
, findOne
, defined indexes or where static methods.
User.find({ name: 'Jane' });
// will return a list of all users with the name "Jane"
User.find({ name: 'Jane' }, { limit: 10 });
// will return a list of all users with the name "Jane" and limited to 10 items
User.findOne({ name: 'Jane' });
// will return a document with a User with the name "Jane" or null in case of not finding it
User.findById('userId');
// will return the user document with the current id.
User.findById('userId', { select: 'name, cards', populate: 'cards' });
// will return the user document with the current id only with the fields name and cards populated
The find options are: link
export interface IFindOptions {
skip?: number;
limit?: number;
sort?: Record<string, SortType>;
populate?: string | string[];
populateMaxDeep?: number;
select?: ISelectType[] | string | string[];
consistency?: SearchConsistency;
noCollection?: boolean;
}
# Advanced use of filter parameter.
const filter = {
$or: [{ price: { $gt: 'amount_val', $isNotNull: true } }, { auto: { $gt: 10 } }, { amount: 10 }],
$and: [
{ price2: { $gt: 1.99, $isNotNull: true } },
{ $or: [{ price3: { $gt: 1.99, $isNotNull: true } }, { id: '20' }] },
],
};
User.find(filter);
// Returns a list of the elements that match the applied filters.
See the chapter on queries for more details on how to use the Query API.
# Deleting
Models have static removeById() function to remove documents matching the given id value. See the API docs for more detail.
User.removeById('userId');
Models have static removeMany() function to remove all documents matching the given condition. See the API docs for more detail.
User.removeMany({ name: { $like: '%JohnDoe%' } });
TIP
The response status will be SUCCESS as long as no error occurs, otherwise it will be FAILURE.
# Updating
Each model
has its own updateById
method for modifying documents in the database without returning them to your application.
See the API docs for more detail.
User.updateById('userId', { age: 30 });
// update document with id equal to 'userId' with age 30.
Models have static replaceById
Same as updateById,except replace the existing document with the given document.
See the API docs for more detail.
User.replaceById('userId', { age: 30, name: 'John' });
// replace document with id equal to 'userId' with age 30 and name John.
Models have static updateMany
function to update all documents matching the given condition.
See the API docs for more detail.
User.updateMany({ name: { $like: '%JohnDoe%' } }, { name: 'John' });
TIP
The response status will be SUCCESS as long as no error occurs, otherwise it will be FAILURE.
Models have static findOneAndUpdate
function to finds a document that matches the conditions of the collection and updates it.
See the API docs for more detail.
User.findOneAndUpdate({ name: { $like: '%John Doe%' } }, { name: 'John' }, { new: true, upsert: true });
TIP
By default the option new and upsert are false
If options.new is true return the document after update otherwise by default return the document before update.
If options.upsert is true insert a document if the document does not exist.
# Handling multilpes Models
When you create a new Model
Ottoman will register it by name.
const User = model('User', userSchema);
// Ottoman under the hood will register in a dictionary object with a key set to model name.
const models = {
"User": UserModel
}
WARNING
Duplicate Model's name will throw an exception notifying about the register model duplication.
# Getting existing Models
You can retrieve a registered Model using the getModel
function.
import {getModel, model} from "ottoman";
const User = model('User', {name: string});
//anywhere else in the app.
const User = getModel('User');
If the name provided doesn't match any registered model undefined
value will be returned.
TIP
Maybe you want to get an existing model and if it's don't exist then attempt to create, the next example could be helpful.
import {getModel, model} from "ottoman";
const User = getModel('User') || model('User', userSchema);
# Next Up
Now that we've covered Models
, let's take a look at Documents.