Gathering detailed insights and metrics for moleculer-db
Gathering detailed insights and metrics for moleculer-db
Gathering detailed insights and metrics for moleculer-db
Gathering detailed insights and metrics for 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
npm install moleculer-db
Typescript
Module System
Min. Node Version
Node Version
NPM Version
68.7
Supply Chain
95.8
Quality
83.4
Maintenance
100
Vulnerability
98.2
License
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
JavaScript (100%)
Verify real, reachable, and deliverable emails with instant MX records, SMTP checks, and disposable email detection.
Total Downloads
1,727,717
Last Day
1,086
Last Week
5,192
Last Month
23,175
Last Year
279,802
MIT License
154 Stars
595 Commits
121 Forks
9 Watchers
30 Branches
48 Contributors
Updated on Feb 17, 2025
Minified
Minified + Gzipped
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
Cumulative downloads
Total Downloads
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
Moleculer service to store entities in database.
1$ npm install moleculer-db --save
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
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.
find
Find entities by query.
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. |
Type: Array.<Object>
List of found entities.
count
Get count of entities by query.
Property | Type | Default | Description |
---|---|---|---|
search | String | - | Search text. |
searchFields | String , Array.<String> | required | Fields list for searching. |
query | Object | - | Query object. Passes to adapter. |
Type: Number
Count of found entities.
list
List entities by filters and pagination results.
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. |
Type: Object
List of found entities and count with pagination info.
create
Create a new entity.
Property | Type | Default | Description |
---|---|---|---|
params | Object | required | Entity to save. |
Type: Object
Saved entity.
insert
Create many new entities.
Property | Type | Default | Description |
---|---|---|---|
entity | Object | - | Entity to save. |
entities | Array.<Object> | - | Entities to save. |
Type: Object
, Array.<Object>
Saved entity(ies).
get
Get entity by ID.
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 . |
Type: Object
, Array.<Object>
Found entity(ies).
update
Update an entity by ID.
After update, clear the cache & call lifecycle events.
Property | Type | Default | Description |
---|---|---|---|
id | any | required | ID of entity. |
Type: Object
Updated entity.
remove
Remove an entity by ID.
Property | Type | Default | Description |
---|---|---|---|
id | any | required | ID of entity. |
Type: Number
Count of removed entities.
sanitizeParams
Sanitize context parameters at find
action.
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | |
params | Object | required |
Type: Object
getById
Get entity(ies) by ID(s).
Property | Type | Default | Description |
---|---|---|---|
id | any , Array.<any> | required | ID or IDs. |
decoding | Boolean | - | Need to decode IDs. |
Type: Object
, Array.<Object>
Found entity(ies).
entityChanged
Clear the cache & call entity lifecycle events
Property | Type | Default | Description |
---|---|---|---|
type | String | required | |
json | Object , Array.<Object> , Number | required | |
ctx | Context | required |
Type: Promise
clearCache
Clear cached entities
Property | Type | Default | Description |
---|---|---|---|
No input parameters. |
Type: Promise
transformDocuments
Transform the fetched documents
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | |
params | Object | required | |
docs | Array , Object | required |
Type: Array
, Object
validateEntity
Validate an entity by validator.
Property | Type | Default | Description |
---|---|---|---|
entity | Object | required |
Type: Promise
encodeID
Encode ID of entity.
Property | Type | Default | Description |
---|---|---|---|
id | any | required |
Type: any
decodeID
Decode ID of entity.
Property | Type | Default | Description |
---|---|---|---|
id | any | required |
Type: any
_find
Find entities by query.
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | Context instance. |
params | Object | - | Parameters. |
Type: Array.<Object>
List of found entities.
_count
Get count of entities by query.
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | Context instance. |
params | Object | - | Parameters. |
Type: Number
Count of found entities.
_list
List entities by filters and pagination results.
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | Context instance. |
params | Object | - | Parameters. |
Type: Object
List of found entities and count.
_create
Create a new entity.
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | Context instance. |
params | Object | - | Parameters. |
Type: Object
Saved entity.
_insert
Create many new entities.
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | Context instance. |
params | Object | - | Parameters. |
Type: Object
, Array.<Object>
Saved entity(ies).
_get
Get entity by ID.
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | Context instance. |
params | Object | - | Parameters. |
Type: Object
, Array.<Object>
Found entity(ies).
_update
Update an entity by ID.
After update, clear the cache & call lifecycle events.
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | Context instance. |
params | Object | - | Parameters. |
Type: Object
Updated entity.
_remove
Remove an entity by ID.
Property | Type | Default | Description |
---|---|---|---|
ctx | Context | required | Context instance. |
params | Object | - | Parameters. |
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.
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!
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}
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}
$ npm test
In development with watching
$ npm run ci
The project is available under the MIT license.
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
Reason
Found 8/10 approved changesets -- score normalized to 8
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
39 existing vulnerabilities detected
Details
Score
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 More