# Interface: IModel ‹T, R

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

R

# Hierarchy

  • IModel

# Constructors

# constructor

+ new IModel(data: T, options?: CastOptions): Document‹T› & T

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

Parameters:

Name Type
data T
options? CastOptions

Returns: Document‹T› & T

# Methods

# count

count(filter?: LogicalWhereExpr‹T›): Promise‹any›

Returns the number of documents that match the query.

example

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

Parameters:

Name Type
filter? LogicalWhereExpr‹T›

Returns: Promise‹any›


# create

createDoc›(doc: Doc): Promise‹Document‹T››

Creates a new document.

example

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

Type parameters:

Doc

Parameters:

Name Type
doc Doc

Returns: Promise‹Document‹T››


# createMany

createManyDoc, Result›(docs: Doc[] | Doc): Promise‹ManyQueryResponseDocument‹Result›››

Creates many documents 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" }]);

Type parameters:

Doc

Result

Parameters:

Name Type
docs Doc[] | Doc

Returns: Promise‹ManyQueryResponseDocument‹Result›››


# dropCollection

dropCollection(collectionName?: undefined | string, scopeName?: undefined | string, options?: undefined | object): Promise‹boolean | undefined›

dropCollection drops a collection from a scope in a bucket.

Parameters:

Name Type Description
collectionName? undefined | string -
scopeName? undefined | string -
options? undefined | object

Returns: Promise‹boolean | undefined›


# find

findDoc›(filter?: LogicalWhereExpr‹Doc›, 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

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.

Type parameters:

Doc

Parameters:

Name Type
filter? LogicalWhereExpr‹Doc›
options? FindOptions

Returns: Promise‹any›


# findById

findByIdResult›(id: string, options?: FindByIdOptions): Promise‹Result›

Retrieves a document by id.

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.

Type parameters:

Result

Parameters:

Name Type
id string
options? FindByIdOptions

Returns: Promise‹Result›

findByIdResult›(id: string, options?: FindByIdOptions): Promise‹Document‹Result››

Type parameters:

Result

Parameters:

Name Type
id string
options? FindByIdOptions

Returns: Promise‹Document‹Result››


# findOne

findOneDoc, Result›(filter?: LogicalWhereExpr‹Doc›, options?: FindOptions): Promise‹Result›

Finds a document.

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.

Type parameters:

Doc

Result

Parameters:

Name Type
filter? LogicalWhereExpr‹Doc›
options? FindOptions

Returns: Promise‹Result›

findOneDoc, Result›(filter?: LogicalWhereExpr‹Doc›, options?: FindOptions): Promise‹Document‹Result››

Type parameters:

Doc

Result

Parameters:

Name Type
filter? LogicalWhereExpr‹Doc›
options? FindOptions

Returns: Promise‹Document‹Result››


# findOneAndUpdate

findOneAndUpdateQuery, Result›(filter?: LogicalWhereExpr‹Query›, doc?: T | Partial‹T›, options?: FindOneAndUpdateOption): Promise‹Result›

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" })

example Using findOneAndUpdate on immutable properties

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.

Type parameters:

Query

Result

Parameters:

Name Type Description
filter? LogicalWhereExpr‹Query› Filter Condition Where Expression
doc? T | Partial‹T› 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. options.strict used for strategy to apply on immutables properties

Returns: Promise‹Result›

findOneAndUpdateQuery, Result›(filter?: LogicalWhereExpr‹Query›, doc?: T | Partial‹T›, options?: FindOneAndUpdateOption): Promise‹Document‹Result››

Type parameters:

Query

Result

Parameters:

Name Type
filter? LogicalWhereExpr‹Query›
doc? T | Partial‹T›
options? FindOneAndUpdateOption

Returns: Promise‹Document‹Result››


# fromData

fromData(data: T | Partial‹T›): ModelTypes‹T›

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 T | Partial‹T›

Returns: ModelTypes‹T›


# removeById

removeById(id: string): Promise‹object›

Removes a document by id.

example

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

Parameters:

Name Type
id string

Returns: Promise‹object›


# removeMany

removeManyDoc, Result›(filter?: LogicalWhereExpr‹Doc›, options?: FindOptions): Promise‹ManyQueryResponse‹Result››

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%' } })
// Could also use:
const result = await User.removeMany({ name:'John Doe' }, { ignoreCase: true })

Type parameters:

Doc

Result

Parameters:

Name Type Description
filter? LogicalWhereExpr‹Doc› Filter Condition Where Expression
options? FindOptions (/classes/findoptions.html#class-findoptions)

Returns: Promise‹ManyQueryResponse‹Result››


# replaceById

replaceByIdDoc, Result›(id: string, data: Doc | Document‹Doc›, options?: MutationFunctionOptions): Promise‹Result›

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

example

const user = await User.replaceById('userId', {name: "John Doe"});

example Using replaceById on immutable properties

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.

Type parameters:

Doc

Result

Parameters:

Name Type
id string
data Doc | Document‹Doc›
options? MutationFunctionOptions

Returns: Promise‹Result›

replaceByIdDoc, Result›(id: string, data: Doc | Document‹Doc›, options?: MutationFunctionOptions): Promise‹Document‹Result››

Type parameters:

Doc

Result

Parameters:

Name Type
id string
data Doc | Document‹Doc›
options? MutationFunctionOptions

Returns: Promise‹Document‹Result››


# updateById

updateByIdDoc, Result›(id: string, data: Doc | Partial‹Doc› | Document‹Doc›, options?: MutationFunctionOptions): Promise‹Result›

Updates a document.

example

const user = await User.updateById('userId', {name: "John Doe"});

example Using updateById on immutable properties

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.

Type parameters:

Doc

Result

Parameters:

Name Type
id string
data Doc | Partial‹Doc› | Document‹Doc›
options? MutationFunctionOptions

Returns: Promise‹Result›

updateByIdDoc, Result›(id: string, data: Doc | Partial‹Doc› | Document‹Doc›, options?: MutationFunctionOptions): Promise‹Document‹Result››

Type parameters:

Doc

Result

Parameters:

Name Type
id string
data Doc | Partial‹Doc› | Document‹Doc›
options? MutationFunctionOptions

Returns: Promise‹Document‹Result››


# updateMany

updateManyQuery, Result›(filter?: LogicalWhereExpr‹Query›, doc?: T | Partial‹T›, options?: UpdateManyOptions): Promise‹ManyQueryResponseDocument‹Result›››

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.

example

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

example Using immutable properties


 // 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();

Type parameters:

Query

Result

Parameters:

Name Type Description
filter? LogicalWhereExpr‹Query› Filter Condition Where Expression
doc? T | Partial‹T› Values for the fields to update
options? UpdateManyOptions (/interfaces/updatemanyoptions.html)

Returns: Promise‹ManyQueryResponseDocument‹Result›››