Moleculer framework has an official set of DB adapters. Use them to persist your data in a database.
Database per serviceMoleculer follows the one database per service pattern. To learn more about this design pattern and its implications check this article. For multiple entities/tables per service approach check FAQ.
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
Try it in your browser!
Base Adapter
Moleculer’s default adapter is based on NeDB. Use it to quickly set up and test you prototype.
Only use this adapter for prototyping and testing. When you are ready to go into production simply swap to Mongo, Mongoose or Sequelize adapters as they all implement common Settings, Actions and Methods.
Install
$ npm install moleculer-db --save |
Usage
; |
More examples can be found on GitHub
Settings
All DB adapters share a common set of 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. |
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. |
idField
does not work with Sequelize adapter as you can freely set your own ID while creating the model.
Customization
As with all mixins, the standard merge algorithm allows you to override the defaults applied by this mixin. For example to disable an action you can set the action to false
in your service.
Example
; |
Actions
DB adapters also implement CRUD operations. These actions are published
methods and can be called by other services.
find
Find entities by query.
Parameters
Property | Type | Default | Description |
---|---|---|---|
populate |
Array.<String> |
- | Populated fields. |
fields |
Array.<String> |
- | Fields filter. |
limit |
Number |
required | Max count of rows. |
offset |
Number |
required | Count of skipped rows. |
sort |
String |
required | Sorted fields. |
search |
String |
required | Search text. |
searchFields |
String |
required | Fields for searching. |
query |
Object |
required | 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 |
required | Search text. |
searchFields |
String |
required | Fields list for searching. |
query |
Object |
required | 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 |
Array.<String> |
- | Populated fields. |
fields |
Array.<String> |
- | Fields filter. |
page |
Number |
required | Page number. |
pageSize |
Number |
required | Size of a page. |
sort |
String |
required | Sorted fields. |
search |
String |
required | Search text. |
searchFields |
String |
required | Fields for searching. |
query |
Object |
required | Query object. Passes to adapter. |
Results
Type: Object
- List of found entities and count.
create
Create a new entity.
Parameters
Property | Type | Default | Description |
---|---|---|---|
- | - | - | - |
No input parameters. |
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 |
Array.<String> |
- | Field list for populate. |
fields |
Array.<String> |
- | 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 |
---|---|---|---|
- | - | - | - |
No input parameters. |
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
DB adapters also has a set of helper methods.
getById
Get entity(ies) by ID(s).
Parameters
Property | Type | Default | Description |
---|---|---|---|
id |
String , Number , Array |
required | ID or IDs. |
decoding |
Boolean |
required | Need to decode IDs. |
Results
Type: Object
, Array.<Object>
- Found entity(ies).
clearCache
Clear cached entities
Parameters
Property | Type | Default | Description |
---|---|---|---|
- | - | - | - |
No input parameters. |
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 |
---|---|---|---|
populate |
Array.<String> |
- | Populated fields. |
fields |
Array.<String> |
- | Fields filter. |
limit |
Number |
required | Max count of rows. |
offset |
Number |
required | Count of skipped rows. |
sort |
String |
required | Sorted fields. |
search |
String |
required | Search text. |
searchFields |
String |
required | Fields for searching. |
query |
Object |
required | 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 |
required | Search text. |
searchFields |
String |
required | Fields list for searching. |
query |
Object |
required | 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 |
Array.<String> |
- | Populated fields. |
fields |
Array.<String> |
- | Fields filter. |
page |
Number |
required | Page number. |
pageSize |
Number |
required | Size of a page. |
sort |
String |
required | Sorted fields. |
search |
String |
required | Search text. |
searchFields |
String |
required | Fields for searching. |
query |
Object |
required | Query object. Passes to adapter. |
Results
Type: Object
List of found entities and count.
_create
Create a new entity.
Parameters
Property | Type | Default | Description |
---|---|---|---|
params |
Object |
- | 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 |
Array.<String> |
- | Field list for populate. |
fields |
Array.<String> |
- | 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 |
---|---|---|---|
params |
Object |
- | Entity to update. |
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.
Data Manipulation
You can easily use Action hooks to modify (e.g. add timestamps, hash user’s passwords or remove sensitive info) before or after saving the data in DB. Hooks will only run before or after actions. If you need to run your data manipulations before or after the this._create(), this._update() or this._remove() methods, you can use the Lifecycle events
Example of hooks adding a timestamp and removing sensitive data
; |
Populating
The service allows you to easily populate fields from other services. For example: 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
broker.createService({ |
Recursive population is also supported. For example, if the users service populates a group field:
broker.createService({ |
Then you can populate the group of a post author or liker like this:
//Recursive population |
The
populate
parameter is available infind
,list
andget
actions.
Lifecycle entity events
There are 6 lifecycle entity events which are called when entities are manipulated.
broker.createService({ |
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.
const DbService = require("moleculer-db"); |
Mongo Adapter
This adapter is based on MongoDB.
Install
$ npm install moleculer-db moleculer-db-adapter-mongo --save |
DependenciesTo use this adapter you need to install MongoDB on you system.
Usage
; |
Options
Example with connection URI
new MongoDBAdapter("mongodb://localhost/moleculer-db") |
Example with connection URI & options
new MongoDBAdapter("mongodb://db-server-hostname/my-db", { |
More MongoDB examples can be found on GitHub
Mongoose Adapter
This adapter is based on Mongoose.
Install
$ npm install moleculer-db moleculer-db-adapter-mongoose mongoose --save |
DependenciesTo use this adapter you need to install MongoDB on you system.
Usage
; |
Options
Example with connection URI
new MongooseAdapter("mongodb://localhost/moleculer-db") |
Example with URI and options
new MongooseAdapter("mongodb://db-server-hostname/my-db", { |
Connect to multiple DBs
If your services are running on separate nodes and you wish to connect to multiple databases then you can use model
in your service definition. On the other hand, if your services are running on a single node and you wish to connect to multiple databases, you should define the schema
that will make multiple connections for you.
More Mongoose examples can be found on GitHub
Sequelize Adapter
SQL adapter (Postgres, MySQL, SQLite & MSSQL) for Moleculer DB service with Sequelize.
Install
$ npm install moleculer-db-adapter-sequelize --save |
You have to install additional packages for your database server:
# For SQLite |
Usage
; |
Options
Every constructor arguments are passed to the Sequelize
constructor. Read more about Sequelize connection.
Example with connection URI
new SqlAdapter("postgres://user:[email protected]:5432/dbname"); |
Example with connection options
new SqlAdapter('database', 'username', 'password', { |
More Sequelize examples can be found on GitHub