{"id":16446,"library":"moleculer-db","title":"Moleculer Database Service","description":"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.","status":"active","version":"0.9.0","language":"javascript","source_language":"en","source_url":"https://github.com/moleculerjs/moleculer-db","tags":["javascript","microservice","moleculer","typescript"],"install":[{"cmd":"npm install moleculer-db","lang":"bash","label":"npm"},{"cmd":"yarn add moleculer-db","lang":"bash","label":"yarn"},{"cmd":"pnpm add moleculer-db","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core microservice framework; moleculer-db is a service mixin for it.","package":"moleculer","optional":false}],"imports":[{"note":"While CommonJS `require` works in Node.js >=22, ESM `import` is the idiomatic standard for modern Node.js development. The `moleculer` framework, and by extension its modules, encourage ESM.","wrong":"const { ServiceBroker } = require('moleculer');","symbol":"ServiceBroker","correct":"import { ServiceBroker } from 'moleculer';"},{"note":"DbService is a default export.","wrong":"import { DbService } from 'moleculer-db';","symbol":"DbService","correct":"import DbService from 'moleculer-db';"},{"note":"When using a specific database adapter, import it directly from its package. Adapters are typically default exports.","wrong":"const MongooseAdapter = require('moleculer-db-adapter-mongoose');","symbol":"MongooseAdapter","correct":"import MongooseAdapter from 'moleculer-db-adapter-mongoose';"}],"quickstart":{"code":"import { ServiceBroker } from 'moleculer';\nimport DbService from 'moleculer-db';\n\nconst broker = new ServiceBroker();\n\n// Create a DB service for 'user' entities using the default NeDB adapter\nbroker.createService({\n    name: 'users',\n    mixins: [DbService],\n\n    settings: {\n        // Define which fields are exposed publicly\n        fields: ['_id', 'username', 'name']\n    },\n\n    afterConnected() {\n        // Seed the DB or perform other post-connection setup\n        console.log('DB Service connected for users!');\n        // Example: this.create({ username: 'initialUser', name: 'Initial Name', status: 1 });\n    }\n});\n\nbroker.start()\n.then(async () => {\n    console.log('Broker started. Performing CRUD operations...');\n\n    // Create a new user\n    const newUser = await broker.call('users.create', {\n        username: 'john',\n        name: 'John Doe',\n        status: 1\n    });\n    console.log('Created user:', newUser);\n\n    // Get all users\n    const allUsers = await broker.call('users.find');\n    console.log('All users:', allUsers);\n\n    // List users with pagination (default page size/max page size apply)\n    const pagedUsers = await broker.call('users.list', { page: 1, pageSize: 5 });\n    console.log('Paged users (page 1):', pagedUsers.rows);\n\n    // Update a user (assuming _id is 'john' for NeDB/default adapter, or a generated ID)\n    // Note: In real scenarios, use the actual _id returned from creation\n    const updatedUser = await broker.call('users.update', { id: newUser._id, name: 'Jane Doe' });\n    console.log('Updated user:', updatedUser);\n\n    // Delete a user\n    await broker.call('users.remove', { id: newUser._id });\n    console.log('User deleted.');\n})\n.catch(err => {\n    console.error('Error starting broker or performing actions:', err);\n    process.exit(1);\n});","lang":"typescript","description":"This quickstart demonstrates how to create a basic Moleculer service using `moleculer-db` with the default NeDB adapter, performing common CRUD operations like create, find, list (with pagination), update, and remove. It shows the mixin pattern for integrating `DbService` into a Moleculer service."},"warnings":[{"fix":"Upgrade your Node.js environment to version 22 or higher. For example, `nvm install 22 && nvm use 22`.","message":"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.","severity":"breaking","affected_versions":">=0.9.0"},{"fix":"Refactor service definitions to use the `mixins` property for extending service schemas, e.g., `mixins: [DbService]` instead of passing a second argument to `createService`.","message":"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.","severity":"breaking","affected_versions":">=0.9.0"},{"fix":"Ensure your project uses a Mongoose version compatible with the adapter (Mongoose 7 or 8 for `moleculer-db-adapter-mongoose@0.10.0+`), alongside Node.js 22+.","message":"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.","severity":"breaking","affected_versions":">=0.10.0 (adapter)"},{"fix":"When using `moleculer-db-adapter-sequelize`, configure your primary key directly in your Sequelize model definition rather than relying on the `idField` setting in `moleculer-db`.","message":"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.","severity":"gotcha","affected_versions":">=0.1.0 (all versions)"},{"fix":"For complex SQL schemas or multiple entities per service, consider custom service actions or a custom adapter. `moleculer-db` is intended for simpler 'one database per service' patterns.","message":"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.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Migrate service definitions to use the `mixins` array for `DbService` integration and schema extensions: `broker.createService({ name: 'my-service', mixins: [DbService, myOtherMixin] })`.","cause":"Attempting to pass schema modifications as a second argument to `broker.createService()` after upgrading to Moleculer v0.15 compatible `moleculer-db` versions.","error":"TypeError: createService() second argument is not a plain object"},{"fix":"Update your Node.js runtime to version 22 or later. Use a version manager like `nvm` for easy switching: `nvm install 22 && nvm use 22`.","cause":"`moleculer-db@0.9.0` (and its compatible adapters) explicitly requires Node.js 22 or newer.","error":"Error: This module requires Node.js version >=22.x.x. Current version is v18.x.x"},{"fix":"Ensure your MongoDB instance is running and accessible at the specified connection URI. Verify firewall rules and connection strings.","cause":"The MongoDB server is not running or is inaccessible from the Moleculer service.","error":"MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017"}],"ecosystem":"npm"}