Skip to content

MongoDB Integration

MongoDB is arguably the most popular NoSQL database in the Node.js ecosystem. DolphJS offers zero-boilerplate auto-initialization for MongoDB when combined with the Mongoose ODM.

Setting up MongoDB is as simple as adding the URL to your dolph_config.yaml.

dolph_config.yaml
database:
mongo:
url: mongodb://127.0.0.1:27017/dolph_app
options:
useNewUrlParser: true
useUnifiedTopology: true

When you start your application using DolphFactory, DolphJS automatically establishes the Mongoose connection pool using the settings from dolph_config.yaml.

If you prefer to skip dolph_config.yaml or want to manually control the connection timing (e.g. for testing or complex setups), you can initialize the database programmatically using autoInitMongo from @dolphjs/packages.

import { autoInitMongo } from '@dolphjs/dolph/packages';
autoInitMongo({
url: 'mongodb://127.0.0.1:27017/dolph_app',
options: {
useNewUrlParser: true,
useUnifiedTopology: true,
}
});

Create your Mongoose schema in a dedicated .model.ts file.

src/product/product.model.ts
import { Schema, Document, model } from 'mongoose';
export interface IProduct extends Document {
title: string;
price: number;
inStock: boolean;
}
const ProductSchema = new Schema(
{
title: { type: String, required: true },
price: { type: Number, required: true },
inStock: { type: Boolean, default: true },
},
{ timestamps: true }
);
export const ProductModel = model<IProduct>('Product', ProductSchema);

Use the @InjectMongo decorator to inject the model into your Dolph Service. This pattern ensures your Service remains testable and decoupled.

src/product/product.service.ts
import { DolphServiceHandler } from '@dolphjs/dolph/classes';
import { Dolph } from '@dolphjs/dolph/common';
import { InjectMongo } from '@dolphjs/dolph/decorators';
import { Model } from 'mongoose';
import { ProductModel, IProduct } from './product.model';
@InjectMongo('productModel', ProductModel)
export class ProductService extends DolphServiceHandler<Dolph> {
// Ensure the property name exactly matches the string 'productModel'
productModel!: Model<IProduct>;
constructor() {
super('productService');
}
async addProduct(data: { title: string; price: number }) {
// Utilize Mongoose's create method via the injected property
const newProduct = await this.productModel.create(data);
return newProduct;
}
async getAllProducts() {
return await this.productModel.find({ inStock: true });
}
}