Skip to main content
Stores in Modelence provide a type-safe interface for MongoDB collections with built-in schema validation, custom methods, and indexing support.

Overview

A Store represents a MongoDB collection with:
  • Type-safe schemas using Modelence schema types (based on Zod)
  • Custom document methods for business logic
  • MongoDB indexes for query performance
  • Search indexes for MongoDB Atlas Search
  • CRUD operations with full TypeScript support

Creating a Store

Define a Store by specifying a collection name and configuration:

Schema Definition

Modelence schemas are based on and closely resemble Zod types. Available schema types include:

Custom Methods

Add custom methods to documents for business logic:

Indexes

For index configuration and examples, see Indexes. The indexes guide covers:
  • MongoDB indexes
  • Atlas searchIndexes
  • indexCreationMode (blocking vs background) and startup behavior with migrations

CRUD Operations

Stores provide comprehensive methods for data operations:

Finding Documents

Inserting Documents

Updating Documents

Deleting Documents

Advanced Operations

Including Stores in Modules

Register stores in your module to automatically provision them:
When your application starts, Modelence will:
  • Provision the collection in MongoDB
  • Create all configured indexes
  • Create all configured search indexes
Stores handle all MongoDB connection management automatically. Just define your Store and include it in a module - Modelence takes care of the rest.

Extending Stores

Use the extend() method to add custom schema fields, indexes, methods, and search indexes to any store, including system collections:
The extend() method creates a new Store instance with merged schema, methods, indexes, and search indexes. The extended store shares the same MongoDB collection as the original.

Best Practices

  1. Define stores per domain - Keep related data in the same module
  2. Plan index strategy - See Indexes for configuration patterns and startup mode tradeoffs
  3. Leverage custom methods - Encapsulate business logic in document methods
  4. Type safety - Let TypeScript guide you with schema-based types
  5. Use Atlas Search intentionally - Use searchIndexes for advanced full-text search use cases
  6. Extend system collections early - Extend system collections like dbUsers before using them in your application
  7. Use sparse indexes - For optional fields with low cardinality, use sparse: true to save space

API Reference

For a complete list of available methods and detailed API documentation, see the Store API Reference.