Moleculer Database Service
moleculer-db is an official service mixin for the Moleculer microservices framework, providing a standardized way to interact with various databases. Its current stable version is 0.9.0, released in March 2026, which is compatible with Moleculer v0.15 and requires Node.js 22.x.x. The library offers common CRUD actions, robust caching, pagination, field filtering, and entity lifecycle events. It is designed with a pluggable adapter architecture, supporting popular databases like MongoDB, PostgreSQL, SQLite, MySQL, MSSQL, and NeDB (for prototyping). A key differentiator is its seamless integration into the Moleculer ecosystem, adhering to the 'database per service' pattern, and simplifying data persistence within a microservice architecture while maintaining active development and regular updates to align with the core framework.
Common errors
-
TypeError: createService() second argument is not a plain object
cause Attempting to pass schema modifications as a second argument to `broker.createService()` after upgrading to Moleculer v0.15 compatible `moleculer-db` versions.fixMigrate service definitions to use the `mixins` array for `DbService` integration and schema extensions: `broker.createService({ name: 'my-service', mixins: [DbService, myOtherMixin] })`. -
Error: This module requires Node.js version >=22.x.x. Current version is v18.x.x
cause `moleculer-db@0.9.0` (and its compatible adapters) explicitly requires Node.js 22 or newer.fixUpdate your Node.js runtime to version 22 or later. Use a version manager like `nvm` for easy switching: `nvm install 22 && nvm use 22`. -
MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
cause The MongoDB server is not running or is inaccessible from the Moleculer service.fixEnsure your MongoDB instance is running and accessible at the specified connection URI. Verify firewall rules and connection strings.
Warnings
- breaking The minimum Node.js version has been bumped to `>=22.x.x` in `moleculer-db@0.9.0` and its related adapters. Older Node.js versions are no longer supported.
- breaking With Moleculer v0.15 compatibility in `moleculer-db@0.9.0`, the `broker.createService(schema, schemaMods)` signature is removed. Service schema modifications must now be done using the `mixins` pattern within the service definition.
- breaking For `moleculer-db-adapter-mongoose@0.10.0`, the minimum Node.js version was bumped to 14, and Mongoose versions 7 & 8 are now supported. While `moleculer-db@0.9.0` now mandates Node.js 22, ensure your Mongoose version is compatible if upgrading this adapter.
- gotcha The `idField` setting in `moleculer-db` is ignored by the `moleculer-db-adapter-sequelize`. With Sequelize, the ID field is typically defined within your model's schema, allowing for custom primary keys.
- gotcha Moleculer DB currently supports only one model/entity per service. While this works well for NoSQL document databases, for SQL databases with multiple and complex relationships, you may need to write a custom adapter or service actions if `moleculer-db`'s features do not suffice.
Install
-
npm install moleculer-db -
yarn add moleculer-db -
pnpm add moleculer-db
Imports
- ServiceBroker
const { ServiceBroker } = require('moleculer');import { ServiceBroker } from 'moleculer'; - DbService
import { DbService } from 'moleculer-db';import DbService from 'moleculer-db';
- MongooseAdapter
const MongooseAdapter = require('moleculer-db-adapter-mongoose');import MongooseAdapter from 'moleculer-db-adapter-mongoose';
Quickstart
import { ServiceBroker } from 'moleculer';
import DbService from 'moleculer-db';
const broker = new ServiceBroker();
// Create a DB service for 'user' entities using the default NeDB adapter
broker.createService({
name: 'users',
mixins: [DbService],
settings: {
// Define which fields are exposed publicly
fields: ['_id', 'username', 'name']
},
afterConnected() {
// Seed the DB or perform other post-connection setup
console.log('DB Service connected for users!');
// Example: this.create({ username: 'initialUser', name: 'Initial Name', status: 1 });
}
});
broker.start()
.then(async () => {
console.log('Broker started. Performing CRUD operations...');
// Create a new user
const newUser = await broker.call('users.create', {
username: 'john',
name: 'John Doe',
status: 1
});
console.log('Created user:', newUser);
// Get all users
const allUsers = await broker.call('users.find');
console.log('All users:', allUsers);
// List users with pagination (default page size/max page size apply)
const pagedUsers = await broker.call('users.list', { page: 1, pageSize: 5 });
console.log('Paged users (page 1):', pagedUsers.rows);
// Update a user (assuming _id is 'john' for NeDB/default adapter, or a generated ID)
// Note: In real scenarios, use the actual _id returned from creation
const updatedUser = await broker.call('users.update', { id: newUser._id, name: 'Jane Doe' });
console.log('Updated user:', updatedUser);
// Delete a user
await broker.call('users.remove', { id: newUser._id });
console.log('User deleted.');
})
.catch(err => {
console.error('Error starting broker or performing actions:', err);
process.exit(1);
});