Skip to main content

MongoService

MongoService<T> is the abstract base class for all @opra/mongodb service classes. It wires up the database connection, codec generation, documentFilter, interceptor chain, and transaction support. You do not extend it directly — use MongoCollectionService, MongoSingletonService, or MongoNestedService instead.

import { MongoService } from '@opra/mongodb';

Hierarchy: ServiceBaseMongoService


Constructor

new MongoService(dataType: Type | string, options?: MongoService.Options)

Methods

for

for<C extends ExecutionContext, P extends Partial<this>>(
context: C | ServiceBase,
overwriteProperties?: P,
overwriteContext?: Partial<C>,
): this & Required<P>

Creates a prototype-chained instance bound to the given context. See Data Services Overview for details.


withTransaction

withTransaction<U>(
callback: (session: ClientSession, _this: this) => U,
options?: TransactionOptions,
): Promise<U>

Executes callback inside a MongoDB transaction. If a transaction is already active on the current context it joins that transaction instead of starting a new one.

await service.for(ctx).withTransaction(async (session) => {
await ordersService.for(ctx, { session }).create(order);
await inventoryService.for(ctx, { session }).updateMany(updates);
});

getCollectionName

getCollectionName(): string

Returns the resolved collection name. Throws if not configured.


getResourceName

getResourceName(): string

Returns the resolved resource name used in error messages. Falls back to getCollectionName().


dataType (getter)

get dataType(): ComplexType

Returns the OPRA ComplexType resolved from the document context. Throws if the type is not registered.


Interfaces

MongoService.Options

All options map directly to instance properties and can be overridden per-request via service.for(context, overwriteProperties).

OptionTypeDescription
contextExecutionContextInitial execution context (from ServiceBase.Options)
dbDb | ((_this) => Db)MongoDB database instance
sessionClientSession | ((_this) => ClientSession)MongoDB client session for transactions
collectionNamestring | ((_this) => string)Target collection name. Defaults to the data type name.
resourceNamestring | ((_this) => string)Resource name used in error messages
scopestringSchema scope applied to codec generation
documentFilterDocumentFilter | DocumentFilter[]Common filter appended to every read and write operation
interceptor(next, command, _this) => Promise<any>Wraps every operation — useful for logging, tracing, or access control
idGenerator(command, _this) => AnyIdCustom ID generator for new documents
onError(error, _this) => void | Promise<void>Error handler invoked on any operation failure

MongoService.CrudOp

type CrudOp = 'create' | 'read' | 'replace' | 'update' | 'delete';

MongoService.CommandInfo

Passed to every lifecycle hook and interceptor. Describes the operation being executed.

PropertyTypeDescription
crudCrudOpThe CRUD category of the operation
methodstringThe method name (e.g. 'findMany', 'update')
byIdbooleanWhether the operation targets a specific document by ID
documentIdAnyIdThe parent document ID, if applicable
nestedIdAnyIdThe nested element ID, if applicable
inputanyThe input payload, if applicable
optionsanyThe operation options

MongoService.DocumentFilter

type DocumentFilter =
| MongoAdapter.FilterInput
| ((args: CommandInfo, _this: MongoService<any>) =>
MongoAdapter.FilterInput | Promise<MongoAdapter.FilterInput> | undefined);

A static filter object or a function that computes the filter per request.


Operation options

Each operation type exposes a dedicated options interface. All extend the corresponding mongodb driver options interface and add an optional filter property.

InterfaceExtendsExtra properties
CreateOptionsmongodb.InsertOneOptionsprojection?
CountOptions<T>mongodb.CountOptionsfilter?
DeleteOptions<T>mongodb.DeleteOptionsfilter?
DeleteManyOptions<T>mongodb.DeleteOptionsfilter?
DistinctOptions<T>mongodb.DistinctOptionsfilter?
ExistsOptions<T>mongodb.CommandOperationOptionsfilter?
FindOneOptions<T>FindManyOptions<T> (without limit)
FindManyOptions<T>mongodb.AggregateOptionsfilter?, projection?, sort?, limit?, skip?, preStages?, postStages?
ReplaceOptions<T>mongodb.FindOneAndReplaceOptionsprojection?, filter?
UpdateOneOptions<T>mongodb.FindOneAndUpdateOptionsprojection?, filter?
UpdateManyOptions<T>mongodb.UpdateOptions (no upsert)filter?