标题:数据库适配器
Moleculer 框架有一组官方 DB 适配器。 可以使用它们在数据库中保存您的数据。
Database per serviceMoleculer遵循* 一个数据库就是一个服务 的模式。 要了解更多关于这种设计模式及其影响的信息,请参考 这篇文章。 至于 *每个服务对应多个实体/表格 的方式请参考 常见问题.
特性概览
- 默认 CRUD 操作
- cached活动
- 分页支持
- 插件式 adapter (NeDB is the default memory adapter for testing & prototyping)
- 官方提供 MongoDB, PostgreSQL, SQLite, MySQL, MSSQL 等适配器。
- 字段过滤
- 联合查询
- ID 编码/解码
- entity 生命周期事件通知
Try it in your browser!
基础适配器
Moleculer 的默认适配器基于 NeDB。 可以用它来快速设置和测试您的原型。
请仅使用此适配器进行原型输入和测试。 当你准备好用于生产环境时,简单地切换到 Mongo, Mongoose 或 Sequelize 适配器就实现了常见的 Settings, Actions 和 Methods
安装
$ npm install moleculer-db --save |
使用
; |
More examples can be found on GitHub
设置
所有数据库适配器共享一组常见的设置:
Property | Type | 默认设置 | 说明 |
---|---|---|---|
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.
示例
; |
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 | 类型 | 默认设置 | 说明 |
---|---|---|---|
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 | 类型 | 默认设置 | 说明 |
---|---|---|---|
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 | 默认设置 | 描述 |
---|---|---|---|
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 | 默认设置 | 描述 |
---|---|---|---|
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 | 默认设置 | 描述 |
---|---|---|---|
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 | 默认设置 | 描述 |
---|---|---|---|
- | - | - | - |
No input parameters.
Results
Type: Object
- Updated entity.
remove
Remove an entity by ID.
Parameters
Property | Type | 默认设置 | 描述 |
---|---|---|---|
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 | 默认设置 | 描述 |
---|---|---|---|
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 | 默认设置 | 描述 |
---|---|---|---|
- | - | - | - |
No input parameters.
Results
Type: Promise
encodeID
Encode ID of entity.
Parameters
Property | Type | 默认设置 | 描述 |
---|---|---|---|
id |
any |
required | - |
Results
Type: any
decodeID
Decode ID of entity.
Parameters
Property | Type | 默认设置 | 描述 |
---|---|---|---|
id |
any |
required | - |
Results
Type: any
_find
Find entities by query.
Parameters
Property | Type | 默认设置 | 描述 |
---|---|---|---|
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 | 默认设置 | 描述 |
---|---|---|---|
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 | 默认设置 | 描述 |
---|---|---|---|
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 | 默认设置 | 描述 |
---|---|---|---|
params |
Object |
- | Entity to save. |
Results
Type: Object
Saved entity.
_insert
Create many new entities.
Parameters
Property | Type | 默认设置 | 描述 |
---|---|---|---|
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 | 默认设置 | 描述 |
---|---|---|---|
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 | 默认设置 | 描述 |
---|---|---|---|
params |
Object |
- | Entity to update. |
Results
Type: Object
Updated entity.
_remove
Remove an entity by ID.
Parameters
Property | Type | 默认设置 | 描述 |
---|---|---|---|
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.
安装
$ npm install moleculer-db moleculer-db-adapter-mongo --save |
DependenciesTo use this adapter you need to install MongoDB on you system.
使用
; |
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.
安装
$ npm install moleculer-db moleculer-db-adapter-mongoose mongoose --save |
DependenciesTo use this adapter you need to install MongoDB on you system.
使用
; |
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.
安装
$ npm install moleculer-db-adapter-sequelize --save |
You have to install additional packages for your database server:
# For SQLite |
使用
; |
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