Skip to main content

Interface: IModel<T, R>

Defined in: model/model.ts:24

Constructor to build a model instance based on schema and 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​

T = any

R​

R = any

Constructors​

Constructor​

new IModel(data, options?): IDocument<T>

Defined in: model/model.ts:29

Creates a document from this model. Implements schema validations, defaults, methods, static and hooks

Parameters​

data​

T

options?​

CastOptions

Returns​

IDocument<T>

Properties​

collectionName​

collectionName: string

Defined in: model/model.ts:523

Return string value with the model collection name

Example​

console.log(User.collectionName)
// "User"

namespace​

namespace: string

Defined in: model/model.ts:513

Return string value with the model context

Example​

console.log(User.namespace)
// `travel-sample`.`inventory`.`user`

Methods​

count()​

count(filter?, options?): Promise<any>

Defined in: model/model.ts:70

Returns the number of documents that match the query.

Parameters​

filter?​

LogicalWhereExpr<T>

options?​

CountOptions

Returns​

Promise<any>

Example​

User.count({ name: { $like: "%Jane%" } })

create()​

create<Doc>(doc, options?): Promise<IDocument<T>>

Defined in: model/model.ts:110

Creates a new document.

Type Parameters​

Doc​

Doc = T

Parameters​

doc​

Doc

options?​

saveOptions

Returns​

Promise<IDocument<T>>

Example​

const user = await User.create({ name: "John Doe" });

createMany()​

createMany<Doc, Result>(docs, options?): Promise<ManyQueryResponse<IDocument<Result>>>

Defined in: model/model.ts:122

Creates many documents at once.

The response status will be SUCCESS as long as no error occurs, otherwise it will be FAILURE.

Type Parameters​

Doc​

Doc = T

Result​

Result = R

Parameters​

docs​

Doc | Doc[]

options?​

saveOptions

Returns​

Promise<ManyQueryResponse<IDocument<Result>>>

Example​

const user = await User.createMany([{ name: "John Doe" }, { name: "Jane Doe" }]);

dropCollection()​

dropCollection(collectionName?, scopeName?, options?): Promise<undefined | boolean>

Defined in: model/model.ts:531

dropCollection drops a collection from a scope in a bucket.

Parameters​

collectionName?​

string

scopeName?​

string

options?​
timeout?​

number

Returns​

Promise<undefined | boolean>


find()​

find<Doc>(filter?, options?): Promise<any>

Defined in: model/model.ts:60

Finds documents.

Type Parameters​

Doc​

Doc = T

Parameters​

filter?​

LogicalWhereExpr<Doc>

options?​

FindOptions

Returns​

Promise<any>

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

User.find({ name: "Jane" }, { ignoreCase: true })
// will return a list of all users with the name "Jane" ignoring case

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' }] },
{name: { $eq: 'John', $ignoreCase: true }}
],
};
User.find(filter)
// Returns a list of the elements that match the applied filters.

findById()​

Call Signature​

findById<Result>(id, options?): Promise<Result>

Defined in: model/model.ts:84

Retrieves a document by id.

Type Parameters​
Result​

Result = R

Parameters​
id​

string

options?​

FindByIdOptions

Returns​

Promise<Result>

Example​
User.findById('userId')
// will return the user document by id.

User.findById('userId', {select: 'name, cards', populate: 'cards'})
// will return the user document by id with only the fields name, and cards populated.

Call Signature​

findById<Result>(id, options?): Promise<IDocument<Result>>

Defined in: model/model.ts:85

Type Parameters​
Result​

Result = R

Parameters​
id​

string

options?​

FindByIdOptions

Returns​

Promise<IDocument<Result>>


findOne()​

Call Signature​

findOne<Doc, Result>(filter?, options?): Promise<Result>

Defined in: model/model.ts:99

Finds a document.

Type Parameters​
Doc​

Doc = T

Result​

Result = R

Parameters​
filter?​

LogicalWhereExpr<Doc>

options?​

FindOptions

Returns​

Promise<Result>

Example​
User.findOne({ name: "Jane" })
// will return a document with a User name of "Jane", or if it doesn't exist, throw a DocumentNotFoundError exception.

User.findOne({ name: "Jane" }, { ignoreCase: true })
// will return a document with a User name of "Jane", ignoring the case.

Call Signature​

findOne<Doc, Result>(filter?, options?): Promise<IDocument<Result>>

Defined in: model/model.ts:100

Type Parameters​
Doc​

Doc = T

Result​

Result = R

Parameters​
filter?​

LogicalWhereExpr<Doc>

options?​

FindOptions

Returns​

Promise<IDocument<Result>>


findOneAndRemove()​

Call Signature​

findOneAndRemove<Query, Result>(filter?): Promise<Result>

Defined in: model/model.ts:491

Finds a document that matches the conditions of the collection and remove it.

Type Parameters​
Query​

Query = T

Result​

Result = R

Parameters​
filter?​

LogicalWhereExpr<Query>

Filter Condition Where Expression

Returns​

Promise<Result>

Example​
const result = await User.findOneAndRemove({ name: { $like: '%John Doe%' } })

Call Signature​

findOneAndRemove<Query, Result>(filter?): Promise<IDocument<Result>>

Defined in: model/model.ts:492

Type Parameters​
Query​

Query = T

Result​

Result = R

Parameters​
filter?​

LogicalWhereExpr<Query>

Returns​

Promise<IDocument<Result>>


findOneAndUpdate()​

Call Signature​

findOneAndUpdate<Query, Result>(filter?, doc?, options?): Promise<Result>

Defined in: model/model.ts:468

Finds a document that matches the conditions of the collection and updates it.

Type Parameters​
Query​

Query = T

Result​

Result = R

Parameters​
filter?​

LogicalWhereExpr<Query>

Filter Condition Where Expression

doc?​

Values for the fields to update

T | Partial<T>

options?​

FindOneAndUpdateOption

FindOneAndUpdateOptions

Return a Model if at least one item matching the condition, otherwise an exception 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. options.strict used for strategy to apply on immutables properties

Returns​

Promise<Result>

Examples​
const result = await User.findOneAndUpdate({ name: { $like: '%John Doe%' } }, { name: "John" })
const cardData = {
cardNumber: '5678 5678 5678 5678',
zipCode: '56789',
};

const cardDataUpdate = {
cardNumber: '4321 4321 4321 4321',
zipCode: '43210',
};

const CardSchema = new Schema({
cardNumber: { type: String, immutable: true },
zipCode: String,
});
const Card = model('Card', CardSchema);
const {id} = await Card.create(cardData);

// with strategy:CAST_STRATEGY.THROW
await Card.findOneAndUpdate({ cardNumber: { $like: '%5678 5678 5678 5678%' } }, cardDataUpdate, {
new: true,
strict: CAST_STRATEGY.THROW,
});
// ImmutableError: Field 'cardNumber' is immutable and current cast strategy is set to 'throw'

// with strategy:true (default)
await Card.findOneAndUpdate({ cardNumber: { $like: '%5678 5678 5678 5678%' } }, cardDataUpdate, {
new: true,
strict: true,
});
const result = await Card.findById(id);
console.log(result); // {cardNumber:'5678 5678 5678 5678', zipCode:'43210'} only zipCode was changed

// with strategy:false
await Card.findOneAndUpdate({ cardNumber: { $like: '%5678 5678 5678 5678%' } }, cardDataUpdate, {
new: true,
strict: false,
});
const result = await Card.findById(id);
console.log(result); // {cardNumber:'4321 4321 4321 4321', zipCode:'43210'} all properties were changed
Throws​

ImmutableError if findOneAndUpdate is strict:CAST_STRATEGY.THROW and try to modify a immutable property.

Call Signature​

findOneAndUpdate<Query, Result>(filter?, doc?, options?): Promise<IDocument<Result>>

Defined in: model/model.ts:474

Type Parameters​
Query​

Query = T

Result​

Result = R

Parameters​
filter?​

LogicalWhereExpr<Query>

doc?​

T | Partial<T>

options?​

FindOneAndUpdateOption

Returns​

Promise<IDocument<Result>>


fromData()​

fromData(data): ModelTypes<T>

Defined in: model/model.ts:263

Creates a document from the given data. Result will be the same that -> new Model(data)

Parameters​

data​

T | Partial<T>

Returns​

ModelTypes<T>

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

query()​

query(params): Query

Defined in: model/model.ts:503

Return a Query instance in the model context

Parameters​

params​

IConditionExpr

Returns​

Query

Example​

const query = User.query({name: 'John Smith'})
console.log(query.build())
// select * from `travel-sample`.`inventory`.`user` where name = 'John Smith'

removeById()​

removeById(id, options?): Promise<{ cas: any; }>

Defined in: model/model.ts:248

Removes a document by id.

Parameters​

id​

string

options?​

CountOptions

Returns​

Promise<{ cas: any; }>

Example​

const result = await User.removeById('userId');

removeMany()​

removeMany<Doc, Result>(filter?, options?): Promise<ManyQueryResponse<Result>>

Defined in: model/model.ts:282

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.

Type Parameters​

Doc​

Doc = T

Result​

Result = string

Parameters​

filter?​

LogicalWhereExpr<Doc>

Filter Condition Where Expression

options?​

FindOptions

Find Options

Returns​

Promise<ManyQueryResponse<Result>>

Example​

const result = await User.removeMany({ name: { $like: '%John Doe%' } })
// Could also use:
const result = await User.removeMany({ name:'John Doe' }, { ignoreCase: true })

replaceById()​

Call Signature​

replaceById<Doc, Result>(id, data, options?): Promise<Result>

Defined in: model/model.ts:228

Same as updateById, except it replaces the existing document with the given document.

Type Parameters​
Doc​

Doc = T

Result​

Result = R

Parameters​
id​

string

data​

Doc | IDocument<Doc>

options?​

MutationFunctionOptions

Returns​

Promise<Result>

Examples​
const user = await User.replaceById('userId', {name: "John Doe"});
const cardData = {
cardNumber: '5678 5678 5678 5678',
zipCode: '56789',
};

const cardDataUpdate = {
cardNumber: '4321 4321 4321 4321',
zipCode: '43210',
};

const CardSchema = new Schema({
cardNumber: { type: String, immutable: true },
zipCode: String,
});
const Card = model('Card', CardSchema);
const {id} = await Card.create(cardData);

// with strategy:CAST_STRATEGY.THROW
await Card.replaceById(id, cardDataUpdate, { strict: CAST_STRATEGY.THROW });
// ImmutableError: Field 'cardNumber' is immutable and current cast strategy is set to 'throw'

// with strategy:true (default)
await Card.replaceById(id, cardDataUpdate, { strict: true });
const result = await Card.findById(id);
console.log(result); // {cardNumber:'5678 5678 5678 5678', zipCode:'43210'} only zipCode was changed

// with strategy:false
await Card.replaceById(id, cardDataUpdate, { strict: false });
const result = await Card.findById(id);
console.log(result); // {cardNumber:'4321 4321 4321 4321', zipCode:'43210'} all properties were changed
Throws​

DocumentNotFoundError if the document not exist.

Throws​

ImmutableError if replaceById is strict:CAST_STRATEGY.THROW and try to modify a immutable property.

Call Signature​

replaceById<Doc, Result>(id, data, options?): Promise<IDocument<Result>>

Defined in: model/model.ts:234

Type Parameters​
Doc​

Doc = T

Result​

Result = R

Parameters​
id​

string

data​

Doc | IDocument<Doc>

options?​

MutationFunctionOptions

Returns​

Promise<IDocument<Result>>


updateById()​

Call Signature​

updateById<Doc, Result>(id, data, options?): Promise<Result>

Defined in: model/model.ts:171

Updates a document.

Type Parameters​
Doc​

Doc = T

Result​

Result = R

Parameters​
id​

string

data​

Doc | Partial<Doc> | IDocument<Doc>

options?​

MutationFunctionOptions

Returns​

Promise<Result>

Examples​
const user = await User.updateById('userId', {name: "John Doe"});
const cardData = {
cardNumber: '5678 5678 5678 5678',
zipCode: '56789',
};

const cardDataUpdate = {
cardNumber: '4321 4321 4321 4321',
zipCode: '43210',
};

const CardSchema = new Schema({
cardNumber: { type: String, immutable: true },
zipCode: String,
});
const Card = model('Card', CardSchema);
const {id} = await Card.create(cardData);

// with strategy:CAST_STRATEGY.THROW
await Card.updateById(id, cardDataUpdate, { strict: CAST_STRATEGY.THROW });
// ImmutableError: Field 'cardNumber' is immutable and current cast strategy is set to 'throw'

// with strategy:true (default)
await Card.updateById(id, cardDataUpdate, { strict: true });
const result = await Card.findById(id);
console.log(result); // {cardNumber:'5678 5678 5678 5678', zipCode:'43210'} only zipCode was changed

// with strategy:false
await Card.updateById(id, cardDataUpdate, { strict: false });
const result = await Card.findById(id);
console.log(result); // {cardNumber:'4321 4321 4321 4321', zipCode:'43210'} all properties were changed
Throws​

ImmutableError if updateById is strict:CAST_STRATEGY.THROW and try to modify a immutable property.

Call Signature​

updateById<Doc, Result>(id, data, options?): Promise<IDocument<Result>>

Defined in: model/model.ts:177

Type Parameters​
Doc​

Doc = T

Result​

Result = R

Parameters​
id​

string

data​

Doc | Partial<Doc> | IDocument<Doc>

options?​

MutationFunctionOptions

Returns​

Promise<IDocument<Result>>


updateMany()​

updateMany<Query, Result>(filter?, doc?, options?): Promise<ManyQueryResponse<IDocument<Result>>>

Defined in: model/model.ts:399

Updates 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.

Type Parameters​

Query​

Query = T

Result​

Result = T

Parameters​

filter?​

LogicalWhereExpr<Query>

Filter Condition Where Expression

doc?​

Values for the fields to update

T | Partial<T>

options?​

UpdateManyOptions

Update Many Options

Returns​

Promise<ManyQueryResponse<IDocument<Result>>>

Examples​

const result = await User.updateMany({ name: { $like: '%John Doe%' } })

// Function helper for example
async function updateManyHelper(result: any[], strict: ApplyStrategy = true) {
// First define the schema
const CardSchema = new Schema({
cardNumber: String,
zipCode: { type: String, immutable: true },
});

//The model is created
const Card = model('CardMany', CardSchema);

// Created elements are stored here
let card1;
let card2;

const batchCreate = async () => {
card1 = await Card.create({ cardNumber: '5678 5678 1111 1111', zipCode: '11111' });
card2 = await Card.create({ cardNumber: '5678 5678 2222 2222', zipCode: '22222' });
};

// Create elements
await batchCreate();

// Update by some criteria
const response: IManyQueryResponse = await Card.updateMany(
{ cardNumber: { $like: '%5678 5678%' } },
{ zipCode: '12345', cardNumber: '0000 0000 0000 0000' },
{ strict },
);
const result1 = await Card.findById(card1.id);
const result2 = await Card.findById(card2.id);

// Reset data before end test round
const cleanUp = async () => await Card.removeMany({ _type: 'CardMany' });
await cleanUp();

// Return results and response
result.push(result1, result2, response);
}

// Store data to check response on each round
let result: any[] = [];

async function testRounds(){

// Round 1: updateMany with strategy:false
await updateManyHelper(result, false);
const [result1, result2, response] = result;
console.log(result1); // {"cardNumber":"0000 0000 0000 0000","zipCode":"12345"} both properties have been changed
console.log(result2); // {"cardNumber":"0000 0000 0000 0000","zipCode":"12345"} both properties have been changed
console.log(response); // {"status":"SUCCESS","message":{"success":2,"match_number":2,"errors":[]}}
result = [];

// Round 2: updateMany with strategy:true
await updateManyHelper(result, true);
const [result1, result2, response] = result;
console.log(result1); // {"cardNumber":"0000 0000 0000 0000","zipCode":"11111"} only cardNumber has changed
console.log(result2); // {"cardNumber":"0000 0000 0000 0000","zipCode":"22222"} only cardNumber has changed
console.log(response); // {"status":"SUCCESS","message":{"success":2,"match_number":2,"errors":[]}}
result = [];

// Round 3: updateMany with strategy:CAST_STRATEGY.THROW
await updateManyHelper(result, CAST_STRATEGY.THROW);
const [result1, result2, response] = result;
console.log(result1); // {"cardNumber":"5678 5678 1111 1111","zipCode":"11111"} only cardNumber has changed
console.log(result2); // {"cardNumber":"5678 5678 2222 2222","zipCode":"22222"} only cardNumber has changed
console.log(response); // {"status":"SUCCESS","message":{"success":2,"match_number":2,"errors":[]}}
result = [];

// RESPONSE FAILURE
// {
// "status": "FAILURE",
// "message": {
// "success": 0,
// "match_number": 2,
// "errors": [
// {
// "status": "FAILURE",
// "exception": "ImmutableError",
// "message": "Field 'zipCode' is immutable and current cast strategy is set to 'throw'"
// },
// {
// "status": "FAILURE",
// "exception": "ImmutableError",
// "message": "Field 'zipCode' is immutable and current cast strategy is set to 'throw'"
// }
// ]
// }
// }
}
// Test rounds are run
testRounds();