0.1.0 • Published 2 years ago

moleculer-orm-mongoose v0.1.0

Weekly downloads
-
License
-
Repository
-
Last release
2 years ago

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

PropertyTypeDefaultDescription
pageSizeNumber10Default page size in list action.
maxPageSizeNumber100Maximum 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

PropertyTypeDefaultDescription
fieldsString, Array.<String>-Fields filter. defaults return all fields in entity.
fieldsString, Array.<String>-Fields filter.
whereObject-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

PropertyTypeDefaultDescription
fieldsString, Array.<String>-Fields filter. defaults return all fields in entity.
limitNumber-Max count of rows.
offsetNumber-Count of skipped rows.
sortString, Array.<String>-Sorted fields. exemple: 'name' for ASC order or '-name' for DESC
searchString, Object-Make LIKE operation in all fields, case object, fields in object.
whereObject-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

PropertyTypeDefaultDescription
searchString, Object-Make LIKE operation in all fields, case object, fields in object.
whereObject-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

PropertyTypeDefaultDescription
fieldsString, Array.<String>-Fields filter. defaults return all fields in entity.
pageNumber-Page number.
pageSizeNumber-Size of a page.
sortString, Array.<String>-Sorted fields. exemple: 'name' for ASC order or '-name' for DESC
searchString, Object-Make LIKE operation in all fields, case object, fields in object.
whereObject-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

PropertyTypeDefaultDescription
paramsObjectrequiredEntity 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

PropertyTypeDefaultDescription
entitiesArray.<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

PropertyTypeDefaultDescription
idanyrequiredID of entity.
...paramsobjectrequiredthe 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

PropertyTypeDefaultDescription
idanyrequiredID 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

PropertyTypeDefaultDescription
ctxContextrequired
paramsObjectrequired

Results

Type: Object

clearCache

Clear cached entities

Parameters

PropertyTypeDefaultDescription

No input parameters.

Results

Type: Promise

toJSON

Transform the fetched documents

Parameters

PropertyTypeDefaultDescription
docsArray, Objectrequireddoc fetched

Results

Type: Array, Object

_find

Find entities by query.

Parameters

PropertyTypeDefaultDescription
ctxContextrequiredContext instance.
paramsObject-Parameters.

Results

Type: Array.<Object>

List of found entities.

_count

Get count of entities by query.

Parameters

PropertyTypeDefaultDescription
ctxContextrequiredContext instance.
paramsObject-Parameters.

Results

Type: Number

Count of found entities.

_list

List entities by filters and pagination results.

Parameters

PropertyTypeDefaultDescription
ctxContextrequiredContext instance.
paramsObject-Parameters.

Results

Type: Object

List of found entities and count.

_create

Create a new entity.

Parameters

PropertyTypeDefaultDescription
ctxContextrequiredContext instance.
paramsObject-Parameters.

Results

Type: Object

Saved entity.

_insert

Create many new entities.

Parameters

PropertyTypeDefaultDescription
ctxContextrequiredContext instance.
paramsObject-Parameters.

Results

Type: Object, Array.<Object>

Saved entity(ies).

_get

Get entity by ID.

Parameters

PropertyTypeDefaultDescription
ctxContextrequiredContext instance.
paramsObject-Parameters.

Results

Type: Object, Array.<Object>

Found entity(ies).

_update

Update an entity by ID.

After update, clear the cache & call lifecycle events.

Parameters

PropertyTypeDefaultDescription
ctxContextrequiredContext instance.
paramsObject-Parameters.

Results

Type: Object

Updated entity.

_remove

Remove an entity by ID.

Parameters

PropertyTypeDefaultDescription
ctxContextrequiredContext instance.
paramsObject-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

0.0.10

2 years ago

0.0.11

2 years ago

0.0.12

2 years ago

0.0.13

2 years ago

0.0.14

2 years ago

0.1.0

2 years ago

0.0.15

2 years ago

0.0.16

2 years ago

0.0.8

2 years ago

0.0.17

2 years ago

0.0.18

2 years ago

0.0.19

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago