BaoModel

new BaoModel(jsDataopt)

Base model that implements core functionality for all models. Do not instantiate this class directly, instead use a subclass, usually that has been generated by the code generator.

Parameters:
NameTypeAttributesDescription
jsDataObject<optional>

The initial data for the model.

Methods

clearConsumedCapacity()

Clear the consumed capacity for the current model instance.

clearRelatedCache(fieldName)

Clear the related cache for a given field.

Parameters:
NameTypeDescription
fieldNamestring

The name of the field to clear.

exists() → {boolean}

Returns true if the object exists. This is particularly useful when checking if an object has been found, since ObjectNotFound will be returned rather than null if an object is not found (so capacity information will also be returned).

Returns:

True if the object exists, false otherwise.

Type: 
boolean

getConsumedCapacity() → {Array.<Object>}

Get the consumed capacity for the current model instance. Every entry in this array will represent a separate operation.

Returns:

The consumed capacity.

Type: 
Array.<Object>

getNumericConsumedCapacity(type, includeRelatedopt) → {number}

Get the number of RCU/WCU consumed by a model instance. Additional capacity is added every time a new operation (finding, saving, loading related data) is performed on the instance. You can reset the consumed capacity by calling BaoModel#clearConsumedCapacity.

Parameters:
NameTypeAttributesDefaultDescription
typestring

Either "read", "write", or "total".

includeRelatedboolean<optional>
false

Whether to include capacity from related objects.

Returns:

The numeric consumed capacity.

Type: 
number

(async) getOrLoadRelatedField(fieldName, loaderContextopt) → {Promise.<Object>}

Get or load a related field. If the field is already loaded, it will be returned without reloading. Otherwise, it will be loaded from the database and returned.

Parameters:
NameTypeAttributesDefaultDescription
fieldNamestring

The name of the field to get or load.

loaderContextObject<optional>
null

Cache context for storing and retrieving items across requests.

Returns:

Returns a promise that resolves to the loaded item.

Type: 
Promise.<Object>

getPrimaryId() → {string}

Get the primary ID for a given object. This is a string that uniquely identifies the object in the database. When using BaoModel.find, this is the id to use. Do not make assumptions about how this id is formatted since it will depend on the model key structure.

Returns:

The primary ID.

Type: 
string

getRelated(fieldName) → {Object}

Get a related field. If the field is not loaded, it will return null.

Parameters:
NameTypeDescription
fieldNamestring

The name of the field to get.

Returns:

The related field.

Type: 
Object

hasChanges() → {boolean}

Returns true if any fields have been modified since the object was last loaded from the database.

Returns:

True if there are changes, false otherwise.

Type: 
boolean

isLoaded() → {boolean}

Returns true if the object has been loaded from the database.

Returns:

True if the object has been loaded, false otherwise.

Type: 
boolean

(async) loadRelatedData(fieldNamesopt, loaderContextopt) → {Promise.<Object>}

Load objects for RelatedField's on the current model instance.

Parameters:
NameTypeAttributesDefaultDescription
fieldNamesArray.<string><optional>
null

The names of the fields to load. If not provided, all related fields will be loaded.

loaderContextObject<optional>
null

Cache context for storing and retrieving items across requests.

Returns:

Returns a promise that resolves to the loaded items and their consumed capacity

Type: 
Promise.<Object>

(async) save(optionsopt) → {Promise.<Object>}

Save the current object to the database. This operation will diff the current state of the object with the state that has been loaded from dynamo to determine which changes need to be saved.

Parameters:
NameTypeAttributesDescription
optionsObject<optional>

Additional options for the save operation.

Properties
NameTypeAttributesDefaultDescription
constraintsObject<optional>
{}

Constraints to validate. Options are:

Properties
NameTypeAttributesDefaultDescription
mustExistboolean<optional>
false

Whether the item must exist.

mustNotExistboolean<optional>
false

Whether the item must not exist.

fieldMatchesArray.<string><optional>
[]

An array of field names that must match the current item's loaded state. This is often used for optimistic locking in conjunction with a BaoFields.VersionField field.

Returns:

Returns a promise that resolves to the updated item.

Type: 
Promise.<Object>

(static) batchFind(primaryIds, loaderContextopt) → {Promise.<Object>}

This is the primary way to load multiple objects given an array of ids. This function should only be used when BaoModel.find or BaoModel#loadRelatedData is not sufficient.

Parameters:
NameTypeAttributesDescription
primaryIdsArray.<string>

The primary IDs of the items to load

loaderContextObject<optional>

Cache context for storing and retrieving items across requests.

Returns:

Returns a promise that resolves to the loaded items and their consumed capacity

Type: 
Promise.<Object>

(static) create(jsUpdates) → {Promise.<Object>}

Create a new item in the database.

Parameters:
NameTypeDescription
jsUpdatesObject

The data to create the item with.

Returns:

Returns a promise that resolves to the created item.

Type: 
Promise.<Object>

(static) delete(primaryId, optionsopt) → {Promise.<Object>}

Delete an existing item in the database.

Parameters:
NameTypeAttributesDescription
primaryIdstring

The primary ID of the item to delete.

optionsObject<optional>

Additional options for the delete operation.

Returns:

Returns a promise that resolves to the deleted item.

Type: 
Promise.<Object>

(static) find(primaryId, optionsopt) → {Promise.<Object>}

Find is the primary way to look up an object given its id. It will return the object if it exists, or an ObjectNotFound instance if it does not. Find supports efficient batch loading and caching. In general, this function should be preferred over BaoModel.batchFind. Find uses batchFind internally, unless batchDelay is set to 0.

Parameters:
NameTypeAttributesDefaultDescription
primaryIdstring

The primary ID of the item to find

optionsObject<optional>
{}

Optional configuration for the find operation

Properties
NameTypeAttributesDefaultDescription
batchDelaynumber<optional>
5

Delay in milliseconds before executing batch request. Set to 0 for immediate individual requests

loaderContextObject<optional>

Cache context for storing and retrieving items across requests. If provided, results will be stored in and retrieved from this context

Throws:

If the batch request times out or other errors occur during the operation

Type
Error
Returns:

Returns a promise that resolves to the found item instance or ObjectNotFound

Type: 
Promise.<Object>

(async, static) findByUniqueConstraint(constraintName, value, loaderContextopt) → {Promise.<Object>}

Find an object by a unique constraint. Any unique constraint can also be used to find an object.

Parameters:
NameTypeAttributesDefaultDescription
constraintNamestring

The name of the unique constraint to use.

valuestring

The value of the unique constraint.

loaderContextObject<optional>
null

Cache context for storing and retrieving items across requests.

Returns:

Returns a promise that resolves to the found item.

Type: 
Promise.<Object>

(static) getPrimaryId(data) → {string}

Static version of BaoModel#getPrimaryId.

Parameters:
NameTypeDescription
dataObject

The data object to get the primary ID for.

Returns:

The primary ID.

Type: 
string

(static) getRelatedObjectsViaMap()

Queries related objects via a mapping table.

This is primary used by the code generator to build helper functions for querying related objects. For most common operations, you should not need to use this method directly.

(static) queryByIndex(indexName, pkValue, skCondition, options) → {Promise.<Object>}

This is the primary method for querying data via a named index or primary key. If possible, you should always specify a sort key condition using skCondition. This will use dynamodb's index to query the data without scanning the partition.

Optionally, you can specify a filter condition to further narrow down the results. Please note that a filter condition will scan anything in the partition that matches the skCondition, so if you haven't specified a skCondition, this will scan the entire partition (and consume more capacity units). However, there may also be times when this works without issue and is more efficient than adding another index and paying for the write overhead of the index.

Parameters:
NameTypeDescription
indexNamestring

The name of the index to query based on the model definition

pkValuestring | Object

The partition key value to query.

skConditionObject | null

Optional sort key condition in the format: { fieldName: value } or { fieldName: { $operator: value } } Supported operators: $between, $beginsWith Example: { status: 'active' } or { createdAt: { $between: [date1, date2] } }

optionsObject

Additional query options

Properties
NameTypeDescription
limitnumber

Maximum number of items to return (default: model.defaultQueryLimit)

directionstring

Sort direction, 'ASC' or 'DESC' (default: 'ASC')

startKeyObject

Exclusive start key for pagination

countOnlyboolean

If true, returns only the count of matching items

filterObject

Additional filter conditions for the query. For full filter syntax, see FilterExpressionBuilder#build

returnWrappedboolean

If false, returns raw DynamoDB items instead of model instances

loadRelatedboolean

If true, loads related models for RelatedFields

relatedFieldsArray.<string>

Array of field names to load related data for (used with loadRelated)

relatedOnlyboolean

Used by mapping tables to return only target objects; loadRelated and a single entry in relatedFields must be provided

Throws:
  • If index name is not found in model

    Type
    Error
  • If sort key condition references wrong field

    Type
    Error
Returns:

Returns an object containing:

  • items: Array of model instances or raw items
  • count: Number of items scanned
  • lastEvaluatedKey: Key for pagination (if more items exist)
  • consumedCapacity: DynamoDB response metadata including ConsumedCapacity
Type: 
Promise.<Object>
Example
// Basic query
const results = await Model.queryByIndex('statusIndex', 'active');

// Query with sort key condition
const results = await Model.queryByIndex('dateIndex', 'user123', {
  createdAt: { $between: [startDate, endDate] }
});

// Query with pagination
const results = await Model.queryByIndex('statusIndex', 'active', null, {
  limit: 10,
  startKey: lastEvaluatedKey
});

// Query with related data
const results = await Model.queryByIndex('userIndex', userId, null, {
  loadRelated: true,
  relatedFields: ['organizationId']
});

(static) queryByPrimaryKey(pkValue, skCondition, options) → {Promise.<Object>}

Queries items by their primary key value with an optional sort key condition

For more details, see queryByIndex. In general, it's recommended to use queryByIndex and give a name to the index. You can do this by adding an index name in the indexes section of the model definition and setting it to primaryKey. For example:

models: TaggedPost: ... indexes: postsForTag: this.primaryKey

Parameters:
NameTypeDescription
pkValue*

The partition key value to query

skConditionObject | null

Optional sort key condition in the format: { fieldName: value } or { fieldName: { $operator: value } }

optionsObject

Query options (same as queryByIndex options)

Returns:

Returns an object containing items, count, lastEvaluatedKey, and consumedCapacity

Type: 
Promise.<Object>

(static) setTestId(testId)

ONLY use this for testing. It allows tests to run in isolation and prevent data from being shared between tests/tests to run in parallel. However, it should not be used outside of this context. For examples, showing how to use this, see the tests.

Parameters:
NameTypeDescription
testIdstring

The ID of the test.

(static) update(primaryId, jsUpdates, optionsopt) → {Promise.<Object>}

Update an existing item in the database.

Parameters:
NameTypeAttributesDescription
primaryIdstring

The primary ID of the item to update.

jsUpdatesObject

The data to update the item with.

optionsObject<optional>

Additional options for the update operation.

Returns:

Returns a promise that resolves to the updated item.

Type: 
Promise.<Object>