Skip to content

In a complex application, you may need to perform additional actions after a database operation. This is where DatabaseTrigger comes in, allowing you to define callbacks for specific database operations on a collection.

Supported Triggers and Contexts

The callback function associated with a trigger receives a DatabaseTriggerContext object. The properties available in this context vary depending on the trigger operation.

Trigger OperationDescriptionContext Data
insert-oneTriggered after a single document insertion.doc: The inserted document.
queryResult: The inserted document.
insert-manyTriggered after multiple document insertions.docs: The array of inserted documents.
queryResult: The array of inserted documents.
update-oneTriggered after updating a single document (using updateOne).query: The query filter used.
update: The update operations applied.
queryResult: The operation result.
find-one-and-updateTriggered after findOneAndUpdate.query: The query filter used.
update: The update operations applied.
queryResult: The updated document.
delete-manyTriggered after removing multiple documents (using deleteMany).query: The query filter used.
queryResult: The operation result.
remove-oneTriggered after removing a single document (using deleteOne).query: The query filter used.
queryResult: The operation result.
find-one-and-deleteTriggered after findOneAndDelete or findOneAndRemove.query: The query filter used.
queryResult: The removed document.
findTriggered after a find query.query: The query filter used.
queryResult: Array of found documents.
find-oneTriggered after a findOne query.query: The query filter used.
queryResult: The found document.
countTriggered after a countDocuments query.query: The query filter used.
queryResult: The count (number).
aggregateTriggered after an aggregation pipeline.pipelines: The aggregation pipeline used.
queryResult: The aggregation result.
distinctTriggered after a distinct query.query: The query filter used.
queryResult: The distinct values.
validateTriggered after document validation.doc: The validated document.
queryResult: The validated document.

Example

typescript
import { DatabaseTrigger } from '@modular-rest/server';

const trigger = new DatabaseTrigger('insert-one', ({ doc, queryResult }) => {
  console.log('New document inserted:', queryResult);
  // Perform additional actions
});

// Use the trigger in a collection definition
const collection = new CollectionDefinition({
  triggers: [trigger]
});

Extended by

Properties

PropertyTypeDescription
callback(context) => voidThe callback function to be executed
operationDatabaseOperationThe database operation that triggers the callback

Methods

applyToSchema()

applyToSchema(schema): void

Applies the trigger to a Mongoose schema

Parameters

ParameterTypeDescription
schemaanyThe mongoose schema to apply the trigger to

Returns

void