Features
- ObjectId mapping. Automatically converts the
_idfield from theObjectIdto astring. - ️️Reactive. Fires events as a document created, updated, or deleted from the database;
- CUD operations timestamps. Automatically sets
createdOn,updatedOn, anddeletedOntimestamps for CUD operations; - Schema validation. Validates your data before saving;
- Paging. Implements high-level paging API;
- Soft delete. By default, documents don’t remove from the collection, but are marked with the
deletedOnfield; - Extendable. API is easily extendable, you can add new methods or override existing ones;
- Outbox support. node-mongo can create collections with
_outboxpostfix that stores all CUD events for implementing the transactional outbox pattern;
Installation
Connect to Database
Usually, you need to define a file calleddb that does two things:
- Creates database instance and connects to the database;
- Exposes factory method
createServiceto create different Services to work with MongoDB;
db.ts
Services
Service is a collection wrapper that adds all node-mongo features. Under the hood it uses Node.js MongoDB native methods.createService method returns the service instance. It accepts two parameters: collection name and ServiceOptions.
user.service.ts
update-user.ts
Schema validation
Node-mongo supports any schema library, but we recommend Zod, due to this ability to generate TypeScript types from the schemas.Zod
Joi
Reactivity
The key feature of thenode-mongo is that each create, update or delete operation publishes a CUD event.
${collectionName}.created${collectionName}.updated${collectionName}.deleted
In-memory events
- Enabled by default;
- Events can be lost on service failure;
- Events are stored in
eventBus(Node.js EventEmitter instance); - For handling these events type you will use Events API;
- Designed for transferring events inside a single Node.js process. Events handlers listens node-mongo
eventBus.
Transactional events
- Can be enabled by setting
{ outbox: true }when creating a service; - Guarantee that every database write will produce an event;
- Events are stored in special collections with
_outboxpostfix; - For handling these events type you will use
watch(method for working with Change Streams) on the outbox table; - Designed for transferring events to messages broker like Kafka. Events handlers should listen to message broker events (You need to implement this layer yourself).
Options and Types
ServiceOptions
CreateConfig
Overrides ServiceOptions parameters for create operations.
ReadConfig
Overrides ServiceOptions parameters for read operations.
UpdateConfig
Overrides ServiceOptions parameters for update operations.
DeleteConfig
Overrides ServiceOptions parameters for delete operations.
