moleculer-orm-mongoose

0.1.0 • Public • Published

Moleculer logo

moleculer-orm-mongoose NPM version

Mongoose wrapper for Moleculer.js Ecosystem. This Library implement Moleculer-orm pattern.

Features

  • default CRUD actions
  • cached actions
  • pagination support
  • fields filtering
  • populating
  • sorting
  • entity lifecycle events for notifications
  • fully customizable

Install

$ npm install moleculer-orm-mongoose --save

Usage

"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));

Settings

Property Type Default Description
pageSize Number 10 Default page size in list action.
maxPageSize Number 100 Maximum page size in list action.

Actions

get Cached action

Return only one entity by ID or by the where param, if not found will throw a NotFoundError.

Parameters

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.

Results

Type: Object, Array.<Object>

Found entity.

Throws

  • NotFoundError - If entity not found.

Example

// 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 Cached action

Find entities by query.

Parameters

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.

Results

Type: Array.<Object>

List of found entities.

Example

// 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);

count Cached action

Get count of entities by query.

Parameters

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.

Results

Type: Number

Count of found entities.

Example

// 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 Cached action

List entities by filters and pagination results.

Parameters

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.

Results

Type: Object

List of found entities and count with pagination info.

Example

// 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

Create a new entity.

Parameters

Property Type Default Description
params Object required Entity to save.

Results

Type: Object

Saved entity.

Example

// Create a new user
broker.call("users.create", { username: "john", name: "John Doe", status: 1 }).then(console.log);

insert

Create many new entities.

Parameters

Property Type Default Description
entities Array.<Object> - Entities to save.

Results

Type: Array.<Object>

Saved entities.

Example

// 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

Update an entity by ID.

After update, clear the cache & call lifecycle events.

Parameters

Property Type Default Description
id any required ID of entity.
...params object required the rest of entity to update.

Results

Type: Object

Updated entity.

Throws

  • NotFoundError - If entity not found.

Example

// Update a user
broker.call("users.update", { id: 5, name: "John Doe" }).then(console.log);

remove

Remove an entity by ID.

Parameters

Property Type Default Description
id any required ID of entity.

Results

Type: Number

Count of removed entities.

Throws

  • NotFoundError - If entity not found.

Example

// Remove a user
broker.call("users.remove", { id: 5 }).then(console.log);

Methods

sanitizeParams

Sanitize context parameters at find action.

Parameters

Property Type Default Description
ctx Context required
params Object required

Results

Type: Object

clearCache

Clear cached entities

Parameters

Property Type Default Description
No input parameters.

Results

Type: Promise

toJSON

Transform the fetched documents

Parameters

Property Type Default Description
docs Array, Object required doc fetched

Results

Type: Array, Object

_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.

Lifecycle entity events

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 a Number instead of entities!

Extend with custom actions

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"
            });
        }
    }
}

Remove default actions

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
    }
}

Test

$ npm test

In development with watching

$ npm run ci

License

The project is available under the MIT license.

Contact

Copyright (c) 2016-2022 MoleculerJS

@moleculerjs @MoleculerJS

Package Sidebar

Install

npm i moleculer-orm-mongoose

Weekly Downloads

285

Version

0.1.0

License

none

Unpacked Size

748 kB

Total Files

22

Last publish

Collaborators

  • caiofilus