A simple helper library for Mongoose projects.
Installation
npm install mongoose-crud-helper
Configuration
Sample usage scenarios are explained below.
Changes to Model.js
You can directly code this to your model.
const MCHelper = require('mongoose-crud-helper');
SchemaName.plugin(MCHelper.changeDocStatus);
SchemaName.plugin(MCHelper.getAllDocs);
SchemaName.plugin(MCHelper.getOneDoc);
Usage
You can directly code this to your controller.
1.changeDocStatus
const data = {
_id:<Your-Object-ID>,
status: '<New-Status>'
};
Model.changeDocStatus(data).then(function(response){
});
2.getAllDocs
More info on customLabels referenced below is available at mongoose-paginate-v2
const where = {"$in": {status: ['active','pending']}};
const fieldsToDisplay = {postName: 1, description: 1, createdOn: 1 };
const myCustomLabels = {
docs: 'data',
nextPage: 'next',
prevPage: 'prev',
totalPages: 'pageCount'
};
const options = {
select: fieldsToDisplay,
page: 1,
limit: 10,
lean: false,
sortBy: 'createdOn',
sortOrder: 'desc',
populate: '',
customLabels: myCustomLabels
};
Model.getAllDocs(where, options).then(function(response){
});
3.getOneDoc
const where = {"$in": {status: ['active','pending']}};
const fieldsToDisplay = {postName: 1, description: 1, createdOn: 1 };
Model.getOneDoc(where, fieldsToDisplay).then(function(response){
});
4.hardDelete
const where = {"_id": ObjectId('57f79499cd3aa1000a5643b7')};
Model.hardDelete(where).then(function(response){
});
5.softDelete
const where = {"_id": ObjectId('57f79499cd3aa1000a5643b7')};
Model.softDelete(where).then(function(response){
});