express-mongoose-common-service

If you use Express.js and Mongoose, these common services may be helpful for you

Usage no npm install needed!

<script type="module">
  import expressMongooseCommonService from 'https://cdn.skypack.dev/express-mongoose-common-service';
</script>

README

If you use Express.js and Mongoose, these common services may be helpful for you

USAGE:

const emcs = require("express-mongoose-common-service");
const testService = emcs.generate(dbTable, identifierName, returnMsg);

OR

import emcs from "express-mongoose-common-service";
const testService = emcs.generate(dbTable, identifierName, returnMsg);

In which,

  1. dbTable: is the mongoose table, ex. db.Test
  2. identifierName: the identifer field in your table, in my case that is 'id'
  3. returnMsg: you can leave this argument empty to use the default value as below
returnMsg = {
  createFailDuplicate: (identifierValue) =>
    `Id ${identifierValue} is already taken.`,
  updateFailValidate: "Record can not be found",
  updateFailDuplicate: (identifierValue) =>
    `Id ${identifierValue} is already taken.`,
};

or override it on your own will.

Methods return on calling the method generate:

  1. getAll
  2. getById
  3. create
  4. update
  5. delete
  6. getAllByUserId
  7. getByIdByUserId
  8. createByUserId
  9. updateByUserId
  10. deleteByUserId
  11. backup
  12. getAllWithPagination
  13. getAllWithPaginationByUserId

To use getAllWithPagination & getAllWithPaginationByUserId, install mongoose-paginate-v2 and add it to your schema before using these functions

Note: getAll, getById, getAllByUserId, getByIdByUserId can use populate by passing populate param as the final param

Note: you should add 'isDeleted' and 'userId' to your table,

With the delete function, we just marked it as isDeleted = true, we are not actually removed it.