Installations
npm install moleculer-db
Developer Guide
Typescript
Yes
Module System
CommonJS
Min. Node Version
>= 8.x.x
Node Version
12.22.12
NPM Version
6.14.16
Score
68.7
Supply Chain
95.8
Quality
83.4
Maintenance
100
Vulnerability
98.2
License
Releases
moleculer-db@0.8.28
Updated on Feb 17, 2025
moleculer-db-adapter-mongoose@0.10.0
Updated on Jan 29, 2025
moleculer-db@0.8.26
Updated on Aug 24, 2024
moleculer-db@0.8.25
Updated on Nov 12, 2023
moleculer-db@0.8.24
Updated on Jul 15, 2023
moleculer-db-adapter-mongoose@0.9.3
Updated on Jul 15, 2023
Contributors
Languages
JavaScript (100%)
validate.email 🚀
Verify real, reachable, and deliverable emails with instant MX records, SMTP checks, and disposable email detection.
Developer
Download Statistics
Total Downloads
1,727,717
Last Day
1,086
Last Week
5,192
Last Month
23,175
Last Year
279,802
GitHub Statistics
MIT License
154 Stars
595 Commits
121 Forks
9 Watchers
30 Branches
48 Contributors
Updated on Feb 17, 2025
Bundle Size
160.68 kB
Minified
49.30 kB
Minified + Gzipped
Package Meta Information
Latest Version
0.8.28
Package Id
moleculer-db@0.8.28
Unpacked Size
204.41 kB
Size
36.75 kB
File Count
27
NPM Version
6.14.16
Node Version
12.22.12
Published on
Feb 17, 2025
Total Downloads
Cumulative downloads
Total Downloads
1,727,717
Last Day
18.9%
1,086
Compared to previous day
Last Week
-2.1%
5,192
Compared to previous week
Last Month
-3.5%
23,175
Compared to previous month
Last Year
-14%
279,802
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
moleculer-db 
Moleculer service to store entities in database.
Features
- default CRUD actions
- cached actions
- pagination support
- pluggable adapter (NeDB is the default memory adapter for testing & prototyping)
- official adapters for MongoDB, PostgreSQL, SQLite, MySQL, MSSQL.
- fields filtering
- populating
- encode/decode IDs
- entity lifecycle events for notifications
Install
1$ npm install moleculer-db --save
Usage
1"use strict"; 2 3const { ServiceBroker } = require("moleculer"); 4const DbService = require("moleculer-db"); 5 6const broker = new ServiceBroker(); 7 8// Create a DB service for `user` entities 9broker.createService({ 10 name: "users", 11 mixins: [DbService], 12 13 settings: { 14 fields: ["_id", "username", "name"] 15 }, 16 17 afterConnected() { 18 // Seed the DB with ˙this.create` 19 } 20}); 21 22broker.start() 23 24// Create a new user 25.then(() => broker.call("users.create", { 26 username: "john", 27 name: "John Doe", 28 status: 1 29})) 30 31// Get all users 32.then(() => broker.call("users.find").then(console.log)); 33 34// List users with pagination 35.then(() => broker.call("users.list", { page: 2, pageSize: 10 }).then(console.log)); 36 37// Get a user 38.then(() => broker.call("users.get", { id: 2 }).then(console.log)); 39 40// Update a user 41.then(() => broker.call("users.update", { id: 2, name: "Jane Doe" }).then(console.log)); 42 43// Delete a user 44.then(() => broker.call("users.remove", { id: 2 }).then(console.log)); 45
Settings
Property | Type | Default | Description |
---|---|---|---|
idField | String | required | Name of ID field. |
fields | Array.<String> | null | Field filtering list. It must be an Array . If the value is null or undefined doesn't filter the fields of entities. |
excludeFields | Array.<String> | null | Exclude fields from list. It must be an Array . |
populates | Array | null | Schema for population. Read more. |
pageSize | Number | required | Default page size in list action. |
maxPageSize | Number | required | Maximum page size in list action. |
maxLimit | Number | required | Maximum value of limit in find action. Default: -1 (no limit) |
entityValidator | Object , function | null | Validator schema or a function to validate the incoming entity in create & 'insert' actions. |
Note:
idField
does not work with Sequelize adapter as you can freely set your own ID while creating the model.
Actions
find

Find entities by query.
Parameters
Property | Type | Default | Description |
---|---|---|---|
populate | String , Array.<String> | required | Populated fields. |
fields | String , Array.<String> | required | Fields filter. |
limit | Number | - | Max count of rows. |
offset | Number | - | Count of skipped rows. |
sort | String | - | Sorted fields. |
search | String | - | Search text. |
searchFields | String , Array.<String> | required | Fields for searching. |
query | Object | - | Query object. Passes to adapter. |
Results
Type: Array.<Object>
List of found entities.
count

Get count of entities by query.
Parameters
Property | Type | Default | Description |
---|---|---|---|
search | String | - | Search text. |
searchFields | String , Array.<String> | required | Fields list for searching. |
query | Object | - | Query object. Passes to adapter. |
Results
Type: Number
Count of found entities.
list

List entities by filters and pagination results.
Parameters
Property | Type | Default | Description |
---|---|---|---|
populate | String , Array.<String> | required | Populated fields. |
fields | String , Array.<String> | required | Fields filter. |
page | Number | - | Page number. |
pageSize | Number | - | Size of a page. |
sort | String | - | Sorted fields. |
search | String | - | Search text. |
searchFields | String , Array.<String> | required | Fields for searching. |
query | Object | - | Query object. Passes to adapter. |
Results
Type: Object
List of found entities and count with pagination info.
create
Create a new entity.
Parameters
Property | Type | Default | Description |
---|---|---|---|
params | Object | required | Entity to save. |
Results
Type: Object
Saved entity.
insert
Create many new entities.
Parameters
Property | Type | Default | Description |
---|---|---|---|
entity | Object | - | Entity to save. |
entities | Array.<Object> | - | Entities to save. |
Results
Type: Object
, Array.<Object>
Saved entity(ies).
get

Get entity by ID.
Parameters
Property | Type | Default | Description |
---|---|---|---|
id | any , Array.<any> | required | ID(s) of entity. |
populate | String , Array.<String> | required | Field list for populate. |
fields | String , Array.<String> | required | Fields filter. |
mapping | Boolean | - | Convert the returned Array to Object where the key is the value of id . |
Results
Type: Object
, Array.<Object>
Found entity(ies).
update
Update an entity by ID.
After update, clear the cache & call lifecycle events.
Parameters
Property | Type | Default | Description |
---|---|---|---|
id | any | required | ID of entity. |
Results
Type: Object
Updated entity.
remove
Remove an entity by ID.
Parameters
Property | Type | Default | Description |
---|---|---|---|
id | any | required | ID of entity. |
Results
Type: Number
Count of removed entities.
Methods
sanitizeParams
Sanitize context parameters at find
action.
Parameters
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | |
params | Object | required |
Results
Type: Object
getById
Get entity(ies) by ID(s).
Parameters
Property | Type | Default | Description |
---|---|---|---|
id | any , Array.<any> | required | ID or IDs. |
decoding | Boolean | - | Need to decode IDs. |
Results
Type: Object
, Array.<Object>
Found entity(ies).
entityChanged
Clear the cache & call entity lifecycle events
Parameters
Property | Type | Default | Description |
---|---|---|---|
type | String | required | |
json | Object , Array.<Object> , Number | required | |
ctx | Context | required |
Results
Type: Promise
clearCache
Clear cached entities
Parameters
Property | Type | Default | Description |
---|---|---|---|
No input parameters. |
Results
Type: Promise
transformDocuments
Transform the fetched documents
Parameters
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | |
params | Object | required | |
docs | Array , Object | required |
Results
Type: Array
, Object
validateEntity
Validate an entity by validator.
Parameters
Property | Type | Default | Description |
---|---|---|---|
entity | Object | required |
Results
Type: Promise
encodeID
Encode ID of entity.
Parameters
Property | Type | Default | Description |
---|---|---|---|
id | any | required |
Results
Type: any
decodeID
Decode ID of entity.
Parameters
Property | Type | Default | Description |
---|---|---|---|
id | any | required |
Results
Type: any
_find
Find entities by query.
Parameters
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | Context instance. |
params | Object | - | Parameters. |
Results
Type: Array.<Object>
List of found entities.
_count
Get count of entities by query.
Parameters
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | Context instance. |
params | Object | - | Parameters. |
Results
Type: Number
Count of found entities.
_list
List entities by filters and pagination results.
Parameters
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | Context instance. |
params | Object | - | Parameters. |
Results
Type: Object
List of found entities and count.
_create
Create a new entity.
Parameters
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | Context instance. |
params | Object | - | Parameters. |
Results
Type: Object
Saved entity.
_insert
Create many new entities.
Parameters
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | Context instance. |
params | Object | - | Parameters. |
Results
Type: Object
, Array.<Object>
Saved entity(ies).
_get
Get entity by ID.
Parameters
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | Context instance. |
params | Object | - | Parameters. |
Results
Type: Object
, Array.<Object>
Found entity(ies).
_update
Update an entity by ID.
After update, clear the cache & call lifecycle events.
Parameters
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | Context instance. |
params | Object | - | Parameters. |
Results
Type: Object
Updated entity.
_remove
Remove an entity by ID.
Parameters
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | Context instance. |
params | Object | - | Parameters. |
Populating
The service supports to populate fields from other services.
E.g.: if you have an author
field in post
entity, you can populate it with users
service by ID of author. If the field is an Array
of IDs, it will populate all entities via only one request.
Example of populate schema
1broker.createService({
2 name: "posts",
3 mixins: [DbService],
4 settings: {
5 populates: {
6 // Shorthand populate rule. Resolve the `voters` values with `users.get` action.
7 "voters": "users.get",
8
9 // Define the params of action call. It will receive only with username & full name of author.
10 "author": {
11 action: "users.get",
12 params: {
13 fields: "username fullName"
14 }
15 },
16
17 // Custom populator handler function
18 "rate"(ids, docs, rule, ctx) {
19 return Promise.resolve(...);
20 }
21 }
22 }
23});
24
25// List posts with populated authors
26broker.call("posts.find", { populate: ["author"]}).then(console.log);
The
populate
parameter is available infind
,list
andget
actions.
Lifecycle entity events
There are 3 lifecycle entity events which are called when entities are manipulated.
1broker.createService({ 2 name: "posts", 3 mixins: [DbService], 4 settings: {}, 5 6 afterConnected() { 7 this.logger.info("Connected successfully"); 8 }, 9 10 entityCreated(json, ctx) { 11 this.logger.info("New entity created!"); 12 }, 13 14 entityUpdated(json, ctx) { 15 // You can also access to Context 16 this.logger.info(`Entity updated by '${ctx.meta.user.name}' user!`); 17 }, 18 19 entityRemoved(json, ctx) { 20 this.logger.info("Entity removed", json); 21 }, 22});
Please note! If you manipulate multiple entities (updateMany, removeMany), the
json
parameter will be aNumber
instead of entities!
Extend with custom actions
Naturally you can extend this service with your custom actions.
1const DbService = require("moleculer-db"); 2 3module.exports = { 4 name: "posts", 5 mixins: [DbService], 6 7 settings: { 8 fields: ["_id", "title", "content", "votes"] 9 }, 10 11 actions: { 12 // Increment `votes` field by post ID 13 vote(ctx) { 14 return this.adapter.updateById(ctx.params.id, { $inc: { votes: 1 } }); 15 }, 16 17 // List posts of an author 18 byAuthors(ctx) { 19 return this.find({ 20 query: { 21 author: ctx.params.authorID 22 }, 23 limit: ctx.params.limit || 10, 24 sort: "-createdAt" 25 }); 26 } 27 } 28}
Remove default actions
According to moleculer documentation you can disable an action when override it with false
1const DbService = require("moleculer-db"); 2 3module.exports = { 4 name: "posts", 5 mixins: [DbService], 6 7 actions: { 8 // Disable find default action 9 find: false 10 } 11}
Test
$ npm test
In development with watching
$ npm run ci
License
The project is available under the MIT license.
Contact
Copyright (c) 2016-2024 MoleculerJS

No vulnerabilities found.
Reason
15 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
Found 8/10 approved changesets -- score normalized to 8
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/ci.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/moleculerjs/moleculer-db/ci.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:20: update your workflow using https://app.stepsecurity.io/secureworkflow/moleculerjs/moleculer-db/ci.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:25: update your workflow using https://app.stepsecurity.io/secureworkflow/moleculerjs/moleculer-db/ci.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/ci.yml:49: update your workflow using https://app.stepsecurity.io/secureworkflow/moleculerjs/moleculer-db/ci.yml/master?enable=pin
- Info: 0 out of 3 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 third-party GitHubAction dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 28 are checked with a SAST tool
Reason
39 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-h5c3-5r3r-rr8q
- Warn: Project is vulnerable to: GHSA-rmvr-2pp2-xj38
- Warn: Project is vulnerable to: GHSA-xx4v-prfh-6cgc
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-4gmj-3p3h-gm8h
- Warn: Project is vulnerable to: GHSA-8jmw-wjr8-2x66
- Warn: Project is vulnerable to: GHSA-pfrx-2q88-qq97
- Warn: Project is vulnerable to: GHSA-rc47-6667-2j5j
- Warn: Project is vulnerable to: GHSA-78xj-cgh5-2h22
- Warn: Project is vulnerable to: GHSA-2p57-rm9w-gvfp
- Warn: Project is vulnerable to: GHSA-35jh-r3h4-6jhm
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-3j8f-xvm3-ffx4
- Warn: Project is vulnerable to: GHSA-4p35-cfcx-8653
- Warn: Project is vulnerable to: GHSA-7f3x-x4pr-wqhj
- Warn: Project is vulnerable to: GHSA-jpp7-7chh-cf67
- Warn: Project is vulnerable to: GHSA-q6wq-5p59-983w
- Warn: Project is vulnerable to: GHSA-j9fq-vwqv-2fm2
- Warn: Project is vulnerable to: GHSA-pqw5-jmp5-px4v
- Warn: Project is vulnerable to: GHSA-p8p7-x288-28g6
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-f5x3-32g6-xq36
- Warn: Project is vulnerable to: GHSA-72xf-g2v4-qvf3
- Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q
- Warn: Project is vulnerable to: GHSA-wf5p-g6vw-rhxx
- Warn: Project is vulnerable to: GHSA-mwcw-c2x4-8c55
- Warn: Project is vulnerable to: GHSA-hrpp-h998-j3pp
- Warn: Project is vulnerable to: GHSA-mxhp-79qh-mcx6
- Warn: Project is vulnerable to: GHSA-93q8-gq69-wqmw
- Warn: Project is vulnerable to: GHSA-7p7h-4mm5-852v
- Warn: Project is vulnerable to: GHSA-g3ch-rx76-35fx
- Warn: Project is vulnerable to: GHSA-mqr2-w7wj-jjgr
- Warn: Project is vulnerable to: GHSA-49j4-86m8-q2jw
- Warn: Project is vulnerable to: GHSA-fpw7-j2hg-69v5
- Warn: Project is vulnerable to: GHSA-4rch-2fh8-94vw
- Warn: Project is vulnerable to: GHSA-pmh2-wpjm-fj45
- Warn: Project is vulnerable to: GHSA-5fg8-2547-mr8q
- Warn: Project is vulnerable to: GHSA-crh6-fp67-6883
Score
4.2
/10
Last Scanned on 2025-03-03
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to moleculer-db
moleculer-db-adapter-mongo
MongoDB native adapter for Moleculer DB service.
moleculer-db-adapter-mongoose
Mongoose adapter for Moleculer DB service
moleculer-db-adapter-couchdb-nano
CouchDB Nano adapter for Moleculer DB service.
moleculer-context-db
A database tool for providing the database session as part of the context