# Class: Model ‹T›
Constructor to build a model instance based on a schema and other options. Provides methods to handle documents of the current collection in the database
example
import { connect, model } from "ottoman";
connect("couchbase://localhost/travel-sample@admin:password");
// Create an `User` model
const User = model('User', { name: String });
# Type parameters
▪ T
# Hierarchy
Document‹T›
↳ Model
# Constructors
# constructor
+ new Model(data
: unknown, options
: object): Model
Overrides void
Creates a document from this model. Implements schema validations, defaults, methods, static and hooks
Parameters:
▪ data: unknown
▪Default value
options: object= {}
Name | Type |
---|---|
skip? | string[] |
strategy? | CAST_STRATEGY |
strict? | undefined | false | true |
Returns: Model
# Methods
# _applyData
▸ _applyData(data
: any, strategy?
: CAST_STRATEGY): void
Inherited from Document._applyData
Allows to easily apply data from an object to current document.
example
const user = new User({name: "John Doe"});
user._applyData({name: "Jane Doe"});
console.log(user) // {name: "Jane Doe"}
Parameters:
Name | Type |
---|---|
data | any |
strategy? | CAST_STRATEGY |
Returns: void
# _depopulate
▸ _depopulate(fieldsName
: string | string[]): this
Inherited from Document._depopulate
Reverts population. Switches back document reference
example
To get in context about the Card and Issue Models see the populate example.
const card = await Card.findById(cardId);
console.log(card.issues); // ['issueId']
await card._populate('issues')
console.log(card.issues); // [{id: 'issueId', title: 'Broken card'}]
card._depopulate('issues')
console.log(card.issues); // ['issueId']
Parameters:
Name | Type |
---|---|
fieldsName | string | string[] |
Returns: this
# _getId
▸ _getId(): string
Inherited from Document._getId
Returns id value, useful when working with dynamic ID_KEY
example
console.log(user._getId()); // 'userId'
console.log(user.id); // 'userId'
Returns: string
# _getIdField
▸ _getIdField(): string
Inherited from Document._getIdField
Returns id key
Returns: string
# _populate
▸ _populate(fieldsName
: string | string[], deep
: number): Promise‹this›
Inherited from Document._populate
Allows to load document references
example
Getting context to explain populate.
const CardSchema = new Schema({
number: String,
zipCode: String,
issues: [{ type: IssueSchema, ref: 'Issue' }],
});
const IssueSchema = new Schema({
title: String,
description: String,
});
const Card = model('Card', CardSchema);
const Issue = model('Issue', CardSchema);
const issue = await Issue.create({ title: 'Broken card' });
const card = await Card.create({
cardNumber: '4242 4242 4242 4242',
zipCode: '42424',
issues: [issue.id],
});
Now we will see how the _populate methods works.
const card = await Card.findById(cardId);
console.log(card.issues); // ['issueId']
await card.populate('issues')
console.log(card.issues); // [{id: 'issueId', title: 'Broken card'}]
Parameters:
Name | Type | Default |
---|---|---|
fieldsName | string | string[] | - |
deep | number | 1 |
Returns: Promise‹this›
# _populated
▸ _populated(fieldName
: string): boolean
Inherited from Document._populated
Allows to know if a document field is populated
example
To get in context about the Card and Issue Models see the populate example.
const card = await Card.findById(cardId);
console.log(card.issues); // ['issueId']
console.log(card._populated('issues')); // false
await card._populate('issues')
console.log(card.issues); // [{id: 'issueId', title: 'Broken card'}]
console.log(card._populated('issues')); // true
Parameters:
Name | Type |
---|---|
fieldName | string |
Returns: boolean
# _validate
▸ _validate(): any
Inherited from Document._validate
Runs schema validations over current document
example
const user = new User({name: "John Doe"});
try {
await user._validate()
} catch(errors) {
console.log(errors)
}
Returns: any
# remove
▸ remove(options
: object): Promise‹any›
Inherited from Document.remove
Removes the document from database
example
const user = User.findById('userId')
await user.remove();
Parameters:
Name | Type | Default |
---|---|---|
options | object | {} |
Returns: Promise‹any›
# save
▸ save(onlyCreate
: boolean): Promise‹this›
Saves or Updates the document
example
const user = new User({name: "John Doe"}); //user document created, it's not saved yet
await user.save(); // user saved into the DB
You also can force save function to only create new Documents by passing true as argument
await user.save(true); // ensure to execute a insert operation
Parameters:
Name | Type | Default |
---|---|---|
onlyCreate | boolean | false |
Returns: Promise‹this›
# toJSON
▸ toJSON(): this
Inherited from Document.toJSON
Returns a Javascript object to be serialized to JSON
Returns: this
# toObject
▸ toObject(): this
Inherited from Document.toObject
Returns a Javascript object with data
Returns: this
# Static
count
▸ count(filter
: LogicalWhereExpr, options
: CountOptions): Promise‹any›
Returns the number of documents that match the query
example
User.count({name: {$like: "%Jane%"}})
Parameters:
Name | Type | Default |
---|---|---|
filter | LogicalWhereExpr | {} |
options | CountOptions | {} |
Returns: Promise‹any›
# Static
create
▸ create(doc
: Record‹string, any›): Promise‹any›
Allows to create a new document
example
const user = await User.create({name: "John Doe"});
Parameters:
Name | Type |
---|---|
doc | Record‹string, any› |
Returns: Promise‹any›
# Static
createMany
▸ createMany(docs
: Record‹string, any›[] | Record‹string, any›): Promise‹ManyQueryResponse›
Allows to create many document at once.
The response status will be SUCCESS as long as no error occurs, otherwise it will be FAILURE.
example
const user = await User.createMany([{name: "John Doe"}, {name: "Jane Doe"}]);
Parameters:
Name | Type |
---|---|
docs | Record‹string, any›[] | Record‹string, any› |
Returns: Promise‹ManyQueryResponse›
# Static
find
▸ find(filter
: LogicalWhereExpr, options
: FindOptions): Promise‹any›
Finds documents.
example
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
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.
Parameters:
Name | Type | Default |
---|---|---|
filter | LogicalWhereExpr | {} |
options | FindOptions | {} |
Returns: Promise‹any›
# Static
findById
▸ findById(id
: string, options
: FindByIdOptions): Promise‹any›
Allows to retrieve a document by id
example
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
Parameters:
Name | Type | Default |
---|---|---|
id | string | - |
options | FindByIdOptions | {} |
Returns: Promise‹any›
# Static
findOne
▸ findOne(filter
: LogicalWhereExpr, options
: FindOptions): Promise‹any›
Finds a document.
example
User.findOne({name: "Jane"})
// will return a document with a User with the name "Jane" or null in case of not finding it
Parameters:
Name | Type | Default |
---|---|---|
filter | LogicalWhereExpr | {} |
options | FindOptions | {} |
Returns: Promise‹any›
# Static
findOneAndUpdate
▸ findOneAndUpdate(filter
: LogicalWhereExpr, doc
: Record‹string, unknown›, options
: FindOneAndUpdateOption): Promise‹any›
Finds a document that matches the conditions of the collection and updates it.
example
const result = await User.findOneAndUpdate({ name: { $like: '%John Doe%' } }, { name: "John" })
Parameters:
Name | Type | Default | Description |
---|---|---|---|
filter | LogicalWhereExpr | {} | Filter Condition Where Expression |
doc | Record‹string, unknown› | - | Values for the fields to update. |
options | FindOneAndUpdateOption | {} | (/interfaces/findoneandupdateoption.html) Return a Model if at least one item matching the condition, otherwise an exception (opens new window) will be thrown. 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. |
Returns: Promise‹any›
# Static
fromData
▸ fromData(data
: any): Model‹any›
Creates a document from the given data Result will be the same that -> new Model(data)
example
const user = User.fromData({name: "John Doe"});
// we create a `user` document, but it isn't saved yet.
await user.save();
// Now user was persisted to DB
Parameters:
Name | Type |
---|---|
data | any |
Returns: Model‹any›
# Static
removeById
▸ removeById(id
: string): Promise‹any›
Allows to remove a document
example
const result = await User.removeById('userId');
Parameters:
Name | Type |
---|---|
id | string |
Returns: Promise‹any›
# Static
removeMany
▸ removeMany(filter
: LogicalWhereExpr, options
: FindOptions): Promise‹ManyQueryResponse›
Deletes all of the documents that match conditions from the collection.
The response status will be SUCCESS as long as no error occurs, otherwise it will be FAILURE.
example
const result = await User.removeMany({ name: { $like: '%John Doe%' } })
Parameters:
Name | Type | Default | Description |
---|---|---|---|
filter | LogicalWhereExpr | {} | Filter Condition Where Expression |
options | FindOptions | {} | (/classes/findoptions.html#class-findoptions) |
Returns: Promise‹ManyQueryResponse›
# Static
replaceById
▸ replaceById(id
: string, data
: any): Promise‹any›
Same as updateById,except replace the existing document with the given document.
example
const user = await User.replaceById('userId', {name: "John Doe"});
throws
DocumentNotFoundError if the document not exist.
Parameters:
Name | Type |
---|---|
id | string |
data | any |
Returns: Promise‹any›
# Static
updateById
▸ updateById(id
: string, data
: any): Promise‹any›
Allows to update a document
example
const user = await User.updateById('userId', {name: "John Doe"});
Parameters:
Name | Type |
---|---|
id | string |
data | any |
Returns: Promise‹any›
# Static
updateMany
▸ updateMany(filter
: LogicalWhereExpr, doc
: Record‹string, unknown›, options
: UpdateManyOptions): Promise‹ManyQueryResponse›
Update all of the documents that match conditions from the collection.
The response status will be SUCCESS as long as no error occurs, otherwise it will be FAILURE.
example
const result = await User.updateMany({ name: { $like: '%John Doe%' } })
Parameters:
Name | Type | Default | Description |
---|---|---|---|
filter | LogicalWhereExpr | {} | Filter Condition Where Expression |
doc | Record‹string, unknown› | - | Values for the fields to update. |
options | UpdateManyOptions | {} | (/interfaces/updatemanyoptions.html) |
Returns: Promise‹ManyQueryResponse›