Mongoose wrapper for Moleculer.js Ecosystem. This Library implement Moleculer-orm pattern.
- default CRUD actions
- cached actions
- pagination support
- fields filtering
- populating
- sorting
- entity lifecycle events for notifications
- fully customizable
$ npm install moleculer-orm-mongoose --save
"use strict";
const { ServiceBroker } = require("moleculer");
const MongooseMixin = require("moleculer-orm-mongoose");
const broker = new ServiceBroker();
// Create a DB service for `user` entities
broker.createService({
name: "users",
mixins: [MongooseMixin],
model : {
name: "users",
fields: {
username: { type: String },
name: { type: String },
status: { type: Number }
}
},
afterConnected() {
// Seed the DB with ˙this.create`
}
});
broker.start()
// Create a new user
.then(() => broker.call("users.create", {
username: "john",
name: "John Doe",
status: 1
}))
// Get all users
.then(() => broker.call("users.find").then(console.log));
// List users with pagination
.then(() => broker.call("users.list", { page: 2, pageSize: 10 }).then(console.log));
// Get a user
.then(() => broker.call("users.get", { id: 2 }).then(console.log));
// Update a user
.then(() => broker.call("users.update", { id: 2, name: "Jane Doe" }).then(console.log));
// Delete a user
.then(() => broker.call("users.remove", { id: 2 }).then(console.log));
Property | Type | Default | Description |
---|---|---|---|
pageSize |
Number |
10 | Default page size in list action. |
maxPageSize |
Number |
100 | Maximum page size in list action. |
Return only one entity by ID or by the where param, if not found will throw a NotFoundError.
Property | Type | Default | Description |
---|---|---|---|
fields |
String , Array.<String>
|
- | Fields filter. defaults return all fields in entity. |
fields |
String , Array.<String>
|
- | Fields filter. |
where |
Object |
- | Make equal operation entity, in only in where keys. |
Type: Object
, Array.<Object>
Found entity.
-
NotFoundError
- If entity not found.
// Get a user by ID
broker.call("users.get", { id: 2 }).then(console.log);
// Get a user by username
broker.call("users.get", { where: { username: "john" } }).then(console.log);
// Get a user by ID with fields filter
broker.call("users.get", { id: 2, fields: ["username", "name"] }).then(console.log);
Find entities by query.
Property | Type | Default | Description |
---|---|---|---|
fields |
String , Array.<String>
|
- | Fields filter. defaults return all fields in entity. |
limit |
Number |
- | Max count of rows. |
offset |
Number |
- | Count of skipped rows. |
sort |
String , Array.<String>
|
- | Sorted fields. exemple: 'name' for ASC order or '-name' for DESC |
search |
String , Object
|
- | Make LIKE operation in all fields, case object, fields in object. |
where |
Object |
- | Make equal operation entity, in only in where keys. |
Type: Array.<Object>
List of found entities.
// Find all users
broker.call("users.find").then(console.log);
// Find all users with fields filter
broker.call("users.find", { fields: ["username", "name"] }).then(console.log);
// Find all users with limit
broker.call("users.find", { limit: 10 }).then(console.log);
// Find all users with offset
broker.call("users.find", { offset: 10 }).then(console.log);
// Find all users with sort
broker.call("users.find", { sort: "name" }).then(console.log);
// Find all users with search
broker.call("users.find", { search: "john" }).then(console.log);
// Find all users with search
broker.call("users.find", { search: { username: "john" } }).then(console.log);
// Find all users with where
broker.call("users.find", { where: { status: 1 } }).then(console.log);
Get count of entities by query.
Property | Type | Default | Description |
---|---|---|---|
search |
String , Object
|
- | Make LIKE operation in all fields, case object, fields in object. |
where |
Object |
- | Make equal operation entity, in only in where keys. |
Type: Number
Count of found entities.
// Count all users
broker.call("users.count").then(console.log);
// Count all users with search
broker.call("users.count", { search: "john" }).then(console.log);
// Count all users with search
broker.call("users.count", { search: { username: "john" } }).then(console.log);
// Count all users with where
broker.call("users.count", { where: { status: 1 } }).then(console.log);
List entities by filters and pagination results.
Property | Type | Default | Description |
---|---|---|---|
fields |
String , Array.<String>
|
- | Fields filter. defaults return all fields in entity. |
page |
Number |
- | Page number. |
pageSize |
Number |
- | Size of a page. |
sort |
String , Array.<String>
|
- | Sorted fields. exemple: 'name' for ASC order or '-name' for DESC |
search |
String , Object
|
- | Make LIKE operation in all fields, case object, fields in object. |
where |
Object |
- | Make equal operation entity, in only in where keys. |
Type: Object
List of found entities and count with pagination info.
// List all users
broker.call("users.list").then(console.log);
// List all users with fields filter
broker.call("users.list", { fields: ["username", "name"] }).then(console.log);
// List all users with page
broker.call("users.list", { page: 2 }).then(console.log);
// List all users with pageSize
broker.call("users.list", { pageSize: 10 }).then(console.log);
// List all users with sort
broker.call("users.list", { sort: "name" }).then(console.log);
// List all users with search
broker.call("users.list", { search: "john" }).then(console.log);
// List all users with search
broker.call("users.list", { search: { username: "john" } }).then(console.log);
Create a new entity.
Property | Type | Default | Description |
---|---|---|---|
params |
Object |
required | Entity to save. |
Type: Object
Saved entity.
// Create a new user
broker.call("users.create", { username: "john", name: "John Doe", status: 1 }).then(console.log);
Create many new entities.
Property | Type | Default | Description |
---|---|---|---|
entities |
Array.<Object> |
- | Entities to save. |
Type: Array.<Object>
Saved entities.
// Create a new user
broker.call("users.insert", [
{ username: "john", name: "John Doe", status: 1 },
{ username: "jane", name: "Jane Doe", status: 1 }
]).then(console.log);
Update an entity by ID.
After update, clear the cache & call lifecycle events.
Property | Type | Default | Description |
---|---|---|---|
id |
any |
required | ID of entity. |
...params |
object |
required | the rest of entity to update. |
Type: Object
Updated entity.
-
NotFoundError
- If entity not found.
// Update a user
broker.call("users.update", { id: 5, name: "John Doe" }).then(console.log);
Remove an entity by ID.
Property | Type | Default | Description |
---|---|---|---|
id |
any |
required | ID of entity. |
Type: Number
Count of removed entities.
-
NotFoundError
- If entity not found.
// Remove a user
broker.call("users.remove", { id: 5 }).then(console.log);
Sanitize context parameters at find
action.
Property | Type | Default | Description |
---|---|---|---|
ctx |
Context |
required | |
params |
Object |
required |
Type: Object
Clear cached entities
Property | Type | Default | Description |
---|---|---|---|
No input parameters. |
Type: Promise
Transform the fetched documents
Property | Type | Default | Description |
---|---|---|---|
docs |
Array , Object
|
required | doc fetched |
Type: Array
, Object
Find entities by query.
Property | Type | Default | Description |
---|---|---|---|
ctx |
Context |
required | Context instance. |
params |
Object |
- | Parameters. |
Type: Array.<Object>
List of found entities.
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 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 a new entity.
Property | Type | Default | Description |
---|---|---|---|
ctx |
Context |
required | Context instance. |
params |
Object |
- | Parameters. |
Type: Object
Saved entity.
Create many new entities.
Property | Type | Default | Description |
---|---|---|---|
ctx |
Context |
required | Context instance. |
params |
Object |
- | Parameters. |
Type: Object
, Array.<Object>
Saved entity(ies).
Get entity by ID.
Property | Type | Default | Description |
---|---|---|---|
ctx |
Context |
required | Context instance. |
params |
Object |
- | Parameters. |
Type: Object
, Array.<Object>
Found entity(ies).
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 an entity by ID.
Property | Type | Default | Description |
---|---|---|---|
ctx |
Context |
required | Context instance. |
params |
Object |
- | Parameters. |
There are 3 lifecycle entity events which are called when entities are manipulated.
broker.createService({
name: "posts",
mixins: [DbService],
settings: {},
afterConnected() {
this.logger.info("Connected successfully");
},
entityCreated(json, ctx) {
this.logger.info("New entity created!");
},
entityUpdated(json, ctx) {
// You can also access to Context
this.logger.info(`Entity updated by '${ctx.meta.user.name}' user!`);
},
entityRemoved(json, ctx) {
this.logger.info("Entity removed", json);
},
});
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.
const MongooseMixin = require("moleculer-orm-mongoose");
module.exports = {
name: "posts",
mixins: [MongooseMixin],
model: {
...
},
actions: {
// Increment `votes` field by post ID
vote(ctx) {
return this.model.updateById(ctx.params.id, { $inc: { votes: 1 } });
},
// List
byName(ctx) {
return this.find({
where: {
name: ctx.params.name
},
limit: ctx.params.limit || 10,
sort: "-createdAt"
});
}
}
}
According to moleculer documentation you can disable an action when override it with false
const MongooseMixin = require("moleculer-orm-mongoose");
module.exports = {
name: "posts",
mixins: [MongooseMixin],
actions: {
// Disable find default action
find: false
}
}
$ npm test
In development with watching
$ npm run ci
The project is available under the MIT license.
Copyright (c) 2016-2022 MoleculerJS