Skip to main content
API Reference / modelence / server / Store Defined in: src/data/store.ts:71 The Store class provides a type-safe interface for MongoDB collections with built-in schema validation and helper methods.

Example

const dbTodos = new Store('todos', {
  schema: {
    title: schema.string(),
    completed: schema.boolean(),
    dueDate: schema.date().optional(),
    userId: schema.userId(),
  },
  methods: {
    isOverdue() {
      return this.dueDate < new Date();
    }
  }
});

Type Parameters

Type ParameterDescription
TSchema extends ModelSchemaThe document schema type
TMethods extends Record<string, (this, …args) => any>Custom methods that will be added to documents

Constructors

Constructor

new Store<TSchema, TMethods>(name, options): Store<TSchema, TMethods>
Defined in: src/data/store.ts:102 Creates a new Store instance

Parameters

ParameterTypeDescription
namestringThe collection name in MongoDB
options{ indexes: IndexDescription[]; methods?: TMethods; schema: TSchema; searchIndexes?: SearchIndexDescription[]; }Store configuration
options.indexesIndexDescription[]MongoDB indexes to create
options.methods?TMethodsCustom methods to add to documents
options.schemaTSchemaDocument schema using Modelence schema types
options.searchIndexes?SearchIndexDescription[]MongoDB Atlas Search

Returns

Store<TSchema, TMethods>

Properties

PropertyModifierTypeDefined in
DocreadonlyEnhancedOmit<InferDocumentType<TSchema>, "_id"> & object & TMethodssrc/data/store.ts:86

Methods

aggregate()

aggregate(pipeline, options?): AggregationCursor<Document>
Defined in: src/data/store.ts:505 Aggregates documents using MongoDB’s aggregation framework

Parameters

ParameterTypeDescription
pipelineDocument[]The aggregation pipeline
options?AggregateOptionsOptional options

Returns

AggregationCursor<Document> The aggregation cursor

bulkWrite()

bulkWrite(operations): Promise<BulkWriteResult>
Defined in: src/data/store.ts:515 Performs a bulk write operation on the collection

Parameters

ParameterTypeDescription
operationsAnyBulkWriteOperation<InferDocumentType<TSchema>>[]The operations to perform

Returns

Promise<BulkWriteResult> The result of the bulk write operation

countDocuments()

countDocuments(query): Promise<number>
Defined in: src/data/store.ts:376 Counts the number of documents that match a query

Parameters

ParameterTypeDescription
queryFilter<InferDocumentType<TSchema>>The query to filter documents

Returns

Promise<number> The number of documents that match the query

deleteMany()

deleteMany(selector): Promise<DeleteResult>
Defined in: src/data/store.ts:494 Deletes multiple documents

Parameters

ParameterTypeDescription
selectorFilter<InferDocumentType<TSchema>>The selector to find the documents to delete

Returns

Promise<DeleteResult> The result of the delete operation

deleteOne()

deleteOne(selector): Promise<DeleteResult>
Defined in: src/data/store.ts:484 Deletes a single document

Parameters

ParameterTypeDescription
selectorFilter<InferDocumentType<TSchema>>The selector to find the document to delete

Returns

Promise<DeleteResult> The result of the delete operation

extend()

extend<TExtendedSchema, TExtendedMethods>(config): Store<TSchema & TExtendedSchema, PreserveMethodsForExtendedSchema<TMethods, TSchema & TExtendedSchema> & TExtendedMethods>
Defined in: src/data/store.ts:169 Extends the store with additional schema fields, indexes, methods, and search indexes. Returns a new Store instance with the extended schema and updated types. Methods from the original store are preserved with updated type signatures.

Example

// Extend the users collection
export const dbUsers = baseUsersCollection.extend({
  schema: {
    firstName: schema.string(),
    lastName: schema.string(),
    companyId: schema.objectId().optional(),
  },
  indexes: [
    { key: { companyId: 1 } },
    { key: { lastName: 1, firstName: 1 } },
  ],
  methods: {
    getFullName() {
      return `${this.firstName} ${this.lastName}`;
    }
  }
});

// Now fully typed with new fields
const user = await dbUsers.findOne({ firstName: 'John' });
console.log(user?.getFullName());

Type Parameters

Type ParameterDefault type
TExtendedSchema extends ModelSchema-
TExtendedMethods extends Record<string, (this, …args) => any>Record<string, never>

Parameters

ParameterTypeDescription
config{ indexes?: IndexDescription[]; methods?: TExtendedMethods; schema?: TExtendedSchema; searchIndexes?: SearchIndexDescription[]; }Additional schema fields, indexes, methods, and search indexes to add
config.indexes?IndexDescription[]-
config.methods?TExtendedMethods-
config.schema?TExtendedSchema-
config.searchIndexes?SearchIndexDescription[]-

Returns

Store<TSchema & TExtendedSchema, PreserveMethodsForExtendedSchema<TMethods, TSchema & TExtendedSchema> & TExtendedMethods> A new Store instance with the extended schema

fetch()

fetch(query, options?): Promise<EnhancedOmit<InferDocumentType<TSchema>, "_id"> & object & TMethods[]>
Defined in: src/data/store.ts:387 Fetches multiple documents, equivalent to Node.js MongoDB driver’s find and toArray methods combined.

Parameters

ParameterTypeDescription
queryFilter<InferDocumentType<TSchema>>The query to filter documents
options?{ limit?: number; skip?: number; sort?: Document; }Options
options.limit?number-
options.skip?number-
options.sort?Document-

Returns

Promise<EnhancedOmit<InferDocumentType<TSchema>, "_id"> & object & TMethods[]> The documents

findById()

findById(id): Promise<null | EnhancedOmit<InferDocumentType<TSchema>, "_id"> & object & TMethods>
Defined in: src/data/store.ts:348 Fetches a single document by its ID

Parameters

ParameterTypeDescription
idstring | ObjectIdThe ID of the document to find

Returns

Promise<null | EnhancedOmit<InferDocumentType<TSchema>, "_id"> & object & TMethods> The document, or null if not found

findOne()

findOne(query, options?): Promise<null | EnhancedOmit<InferDocumentType<TSchema>, "_id"> & object & TMethods>
Defined in: src/data/store.ts:308

Parameters

ParameterType
queryFilter<InferDocumentType<TSchema>>
options?FindOptions<Document>

Returns

Promise<null | EnhancedOmit<InferDocumentType<TSchema>, "_id"> & object & TMethods>

getDatabase()

getDatabase(): Db
Defined in: src/data/store.ts:524 Returns the raw MongoDB database instance for advanced operations

Returns

Db The MongoDB database instance

Throws

Error if the store is not provisioned

getName()

getName(): string
Defined in: src/data/store.ts:122

Returns

string

insertMany()

insertMany(documents): Promise<InsertManyResult<Document>>
Defined in: src/data/store.ts:413 Inserts multiple documents

Parameters

ParameterTypeDescription
documentsOptionalUnlessRequiredId<InferDocumentType<TSchema>>[]The documents to insert

Returns

Promise<InsertManyResult<Document>> The result of the insert operation

insertOne()

insertOne(document): Promise<InsertOneResult<Document>>
Defined in: src/data/store.ts:401 Inserts a single document

Parameters

ParameterTypeDescription
documentOptionalUnlessRequiredId<InferDocumentType<TSchema>>The document to insert

Returns

Promise<InsertOneResult<Document>> The result of the insert operation

rawCollection()

rawCollection(): Collection<InferDocumentType<TSchema>>
Defined in: src/data/store.ts:533 Returns the raw MongoDB collection instance for advanced operations

Returns

Collection<InferDocumentType<TSchema>> The MongoDB collection instance

Throws

Error if the store is not provisioned

renameFrom()

renameFrom(oldName, options?): Promise<void>
Defined in: src/data/store.ts:542 Renames an existing collection to this store’s name, used for migrations

Parameters

ParameterTypeDescription
oldNamestringThe previous name of the collection
options?{ session?: ClientSession; }-
options.session?ClientSession-

Returns

Promise<void>

Throws

Error if the old collection doesn’t exist or if this store’s collection already exists

requireById()

requireById(id, errorHandler?): Promise<EnhancedOmit<InferDocumentType<TSchema>, "_id"> & object & TMethods>
Defined in: src/data/store.ts:360 Fetches a single document by its ID, or throws an error if not found

Parameters

ParameterTypeDescription
idstring | ObjectIdThe ID of the document to find
errorHandler?() => ErrorOptional error handler to return a custom error if the document is not found

Returns

Promise<EnhancedOmit<InferDocumentType<TSchema>, "_id"> & object & TMethods> The document

requireOne()

requireOne(query, options?, errorHandler?): Promise<EnhancedOmit<InferDocumentType<TSchema>, "_id"> & object & TMethods>
Defined in: src/data/store.ts:313

Parameters

ParameterType
queryFilter<InferDocumentType<TSchema>>
options?FindOptions<Document>
errorHandler?() => Error

Returns

Promise<EnhancedOmit<InferDocumentType<TSchema>, "_id"> & object & TMethods>

updateMany()

updateMany(selector, update, options?): Promise<UpdateResult<Document>>
Defined in: src/data/store.ts:456 Updates multiple documents

Parameters

ParameterTypeDescription
selectorFilter<InferDocumentType<TSchema>>The selector to find the documents to update
updateUpdateFilter<InferDocumentType<TSchema>>The MongoDB modifier to apply to the documents
options?{ session?: ClientSession; }-
options.session?ClientSession-

Returns

Promise<UpdateResult<Document>> The result of the update operation

updateOne()

updateOne(selector, update): Promise<UpdateResult<Document>>
Defined in: src/data/store.ts:426 Updates a single document

Parameters

ParameterTypeDescription
selectorstring | ObjectId | Filter<InferDocumentType<TSchema>>The selector to find the document to update
updateUpdateFilter<InferDocumentType<TSchema>>The update to apply to the document

Returns

Promise<UpdateResult<Document>> The result of the update operation

upsertMany()

upsertMany(selector, update): Promise<UpdateResult<Document>>
Defined in: src/data/store.ts:471 Updates multiple documents, or inserts them if they don’t exist

Parameters

ParameterTypeDescription
selectorFilter<InferDocumentType<TSchema>>The selector to find the documents to update
updateUpdateFilter<InferDocumentType<TSchema>>The MongoDB modifier to apply to the documents

Returns

Promise<UpdateResult<Document>> The result of the update operation

upsertOne()

upsertOne(selector, update): Promise<UpdateResult<Document>>
Defined in: src/data/store.ts:440 Updates a single document, or inserts it if it doesn’t exist

Parameters

ParameterTypeDescription
selectorstring | ObjectId | Filter<InferDocumentType<TSchema>>The selector to find the document to update
updateUpdateFilter<InferDocumentType<TSchema>>The MongoDB modifier to apply to the document

Returns

Promise<UpdateResult<Document>> The result of the update operation

vectorSearch()

vectorSearch(params): Promise<AggregationCursor<Document>>
Defined in: src/data/store.ts:587 Performs a vector similarity search using MongoDB Atlas Vector Search

Example

const results = await store.vectorSearch({
  field: 'embedding',
  embedding: [0.1, 0.2, 0.3, ...],
  numCandidates: 100,
  limit: 10,
  projection: { title: 1, description: 1 }
});

Parameters

ParameterTypeDescription
params{ embedding: number[]; field: string; indexName?: string; limit?: number; numCandidates?: number; projection?: Document; }Vector search parameters
params.embeddingnumber[]The query vector to search for
params.fieldstringThe field name containing the vector embeddings
params.indexName?stringName of index (default: field + VectorSearch)
params.limit?numberMaximum number of results to return (default: 10)
params.numCandidates?numberNumber of nearest neighbors to consider (default: 100)
params.projection?DocumentAdditional fields to include in the results

Returns

Promise<AggregationCursor<Document>> An aggregation cursor with search results and scores

vectorIndex()

static vectorIndex(params): object
Defined in: src/data/store.ts:650 Creates a MongoDB Atlas Vector Search index definition

Example

const store = new Store('documents', {
  schema: {
    title: schema.string(),
    embedding: schema.array(schema.number()),
  },
  indexes: [],
  searchIndexes: [
    Store.vectorIndex({
      field: 'embedding',
      dimensions: 1536,
      similarity: 'cosine'
    })
  ]
});

Parameters

ParameterTypeDescription
params{ dimensions: number; field: string; indexName?: string; similarity?: "cosine" | "euclidean" | "dotProduct"; }Vector index parameters
params.dimensionsnumberThe number of dimensions in the vector embeddings
params.fieldstringThe field name to create the vector index on
params.indexName?stringName of index (default: field + VectorSearch)
params.similarity?"cosine" | "euclidean" | "dotProduct"The similarity metric to use (default: ‘cosine’)

Returns

object A search index description object
NameTypeDefault valueDefined in
definitionobject-src/data/store.ts:664
definition.fieldsobject[]-src/data/store.ts:665
namestring-src/data/store.ts:663
typestring'vectorSearch'src/data/store.ts:662