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
Name | Type |
---|---|
T | any |
R | any |
Constructors
constructor
• new IModel(data
, options?
)
Creates a document from this model. Implements schema validations, defaults, methods, static and hooks
Parameters
Name | Type |
---|---|
data | T |
options? | CastOptions |
Defined in
Properties
collectionName
• collectionName: string
Return string value with the model collection name
Example
console.log(User.collectionName)
// "User"
Defined in
namespace
• namespace: string
Return string value with the model context
Example
console.log(User.namespace)
// `travel-sample`.`inventory`.`user`
Defined in
Methods
count
▸ count(filter?
, options?
): Promise
<any
>
Returns the number of documents that match the query.
Example
User.count({ name: { $like: "%Jane%" } })
Parameters
Name | Type |
---|---|
filter? | LogicalWhereExpr <T > |
options? | CountOptions |
Returns
Promise
<any
>
Defined in
create
▸ create<Doc
>(doc
, options?
): Promise
<IDocument
<T
>>
Creates a new document.
Example
const user = await User.create({ name: "John Doe" });
Type parameters
Name | Type |
---|---|
Doc | T |
Parameters
Name | Type |
---|---|
doc | Doc |
options? | saveOptions |
Returns
Promise
<IDocument
<T
>>
Defined in
createMany
▸ createMany<Doc
, Result
>(docs
, options?
): Promise
<ManyQueryResponse
<IDocument
<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
Name | Type |
---|---|
Doc | T |
Result | R |
Parameters
Name | Type |
---|---|
docs | Doc | Doc [] |
options? | saveOptions |
Returns
Promise
<ManyQueryResponse
<IDocument
<Result
>>>
Defined in
dropCollection
▸ dropCollection(collectionName?
, scopeName?
, options?
): Promise
<undefined
| boolean
>
dropCollection drops a collection from a scope in a bucket.
Parameters
Name | Type |
---|---|
collectionName? | string |
scopeName? | string |
options? | Object |
options.timeout? | number |
Returns
Promise
<undefined
| boolean
>
Defined in
find
▸ find<Doc
>(filter?
, options?
): 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
Name | Type |
---|---|
Doc | T |
Parameters
Name | Type |
---|---|
filter? | LogicalWhereExpr <Doc > |
options? | FindOptions |
Returns
Promise
<any
>
Defined in
findById
▸ findById<Result
>(id
, options?
): 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
Name | Type |
---|---|
Result | R |
Parameters
Name | Type |
---|---|
id | string |
options? | FindByIdOptions |
Returns
Promise
<Result
>
Defined in
▸ findById<Result
>(id
, options?
): Promise
<IDocument
<Result
>>
Type parameters
Name | Type |
---|---|
Result | R |
Parameters
Name | Type |
---|---|
id | string |
options? | FindByIdOptions |
Returns
Promise
<IDocument
<Result
>>
Defined in
findOne
▸ findOne<Doc
, Result
>(filter?
, options?
): 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
Name | Type |
---|---|
Doc | T |
Result | R |
Parameters
Name | Type |
---|---|
filter? | LogicalWhereExpr <Doc > |
options? | FindOptions |
Returns
Promise
<Result
>
Defined in
▸ findOne<Doc
, Result
>(filter?
, options?
): Promise
<IDocument
<Result
>>
Type parameters
Name | Type |
---|---|
Doc | T |
Result | R |
Parameters
Name | Type |
---|---|
filter? | LogicalWhereExpr <Doc > |
options? | FindOptions |
Returns
Promise
<IDocument
<Result
>>
Defined in
findOneAndRemove
▸ findOneAndRemove<Query
, Result
>(filter?
): Promise
<Result
>
Finds a document that matches the conditions of the collection and remove it.
Example
const result = await User.findOneAndRemove({ name: { $like: '%John Doe%' } })
Type parameters
Name | Type |
---|---|
Query | T |
Result | R |
Parameters
Name | Type | Description |
---|---|---|
filter? | LogicalWhereExpr <Query > | Filter Condition Where Expression |
Returns
Promise
<Result
>
Defined in
▸ findOneAndRemove<Query
, Result
>(filter?
): Promise
<IDocument
<Result
>>
Type parameters
Name | Type |
---|---|
Query | T |
Result | R |
Parameters
Name | Type |
---|---|
filter? | LogicalWhereExpr <Query > |
Returns
Promise
<IDocument
<Result
>>
Defined in
findOneAndUpdate
▸ findOneAndUpdate<Query
, Result
>(filter?
, doc?
, options?
): 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
Name | Type |
---|---|
Query | T |
Result | R |
Parameters
Name | Type | Description |
---|---|---|
filter? | LogicalWhereExpr <Query > | Filter Condition Where Expression |
doc? | T | Partial <T > | Values for the fields to update |
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
>
Defined in
▸ findOneAndUpdate<Query
, Result
>(filter?
, doc?
, options?
): Promise
<IDocument
<Result
>>
Type parameters
Name | Type |
---|---|
Query | T |
Result | R |
Parameters
Name | Type |
---|---|
filter? | LogicalWhereExpr <Query > |
doc? | T | Partial <T > |
options? | FindOneAndUpdateOption |
Returns
Promise
<IDocument
<Result
>>
Defined in
fromData
▸ fromData(data
): ModelTypes
<T
, 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 | T | Partial <T > |
Returns
ModelTypes
<T
, any
>
Defined in
query
▸ query(params
): Query
Return a Query instance in the model context
Example
const query = User.query({name: 'John Smith'})
console.log(query.build())
// select * from `travel-sample`.`inventory`.`user` where name = 'John Smith'
Parameters
Name | Type |
---|---|
params | IConditionExpr |
Returns
Defined in
removeById
▸ removeById(id
, options?
): Promise
<{ cas
: any
}>
Removes a document by id.
Example
const result = await User.removeById('userId');
Parameters
Name | Type |
---|---|
id | string |
options? | CountOptions |
Returns
Promise
<{ cas
: any
}>
Defined in
removeMany
▸ removeMany<Doc
, Result
>(filter?
, options?
): 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
Name | Type |
---|---|
Doc | T |
Result | string |
Parameters
Name | Type | Description |
---|---|---|
filter? | LogicalWhereExpr <Doc > | Filter Condition Where Expression |
options? | FindOptions | Find Options |
Returns
Promise
<ManyQueryResponse
<Result
>>
Defined in
replaceById
▸ replaceById<Doc
, Result
>(id
, data
, options?
): 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
Name | Type |
---|---|
Doc | T |
Result | R |
Parameters
Name | Type |
---|---|
id | string |
data | Doc | IDocument <Doc > |
options? | MutationFunctionOptions |
Returns
Promise
<Result
>
Defined in
▸ replaceById<Doc
, Result
>(id
, data
, options?
): Promise
<IDocument
<Result
>>
Type parameters
Name | Type |
---|---|
Doc | T |
Result | R |
Parameters
Name | Type |
---|---|
id | string |
data | Doc | IDocument <Doc > |
options? | MutationFunctionOptions |
Returns
Promise
<IDocument
<Result
>>
Defined in
updateById
▸ updateById<Doc
, Result
>(id
, data
, options?
): 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
Name | Type |
---|---|
Doc | T |
Result | R |
Parameters
Name | Type |
---|---|
id | string |
data | Doc | Partial <Doc > | IDocument <Doc > |
options? | MutationFunctionOptions |
Returns
Promise
<Result
>
Defined in
▸ updateById<Doc
, Result
>(id
, data
, options?
): Promise
<IDocument
<Result
>>
Type parameters
Name | Type |
---|---|
Doc | T |
Result | R |
Parameters
Name | Type |
---|---|
id | string |
data | Doc | Partial <Doc > | IDocument <Doc > |
options? | MutationFunctionOptions |
Returns
Promise
<IDocument
<Result
>>
Defined in
updateMany
▸ updateMany<Query
, Result
>(filter?
, doc?
, options?
): Promise
<ManyQueryResponse
<IDocument
<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
Name | Type |
---|---|
Query | T |
Result | T |
Parameters
Name | Type | Description |
---|---|---|
filter? | LogicalWhereExpr <Query > | Filter Condition Where Expression |
doc? | T | Partial <T > | Values for the fields to update |
options? | UpdateManyOptions | Update Many Options |
Returns
Promise
<ManyQueryResponse
<IDocument
<Result
>>>