mongoose-wrapper-simple
v1.0.1
Published
Mongoose wrapper with default schema, auto timestamps, soft-delete pre-action hooks and easy pagination
Maintainers
Readme
Mongoose Wrapper Simple
Simple mongoose wrapper with default schema, soft-delete pre-action hooks and easy pagination. Sample provided in TypeScript.
Installation
npm i mongoose-wrapper-simple
mongooseis a peer dependency (supports Mongoose^9.x). npm 7+ installs it automatically when not already present.mongoose-paginate-v2is installed automatically as a runtime dependency. No other@types/*packages are required to use this library (the published declarations only referencemongoosetypes).
Local development (file: dependency)
Use this package from another project on the same machine without publishing to the registry:
// other-project/package.json
{
"dependencies": {
"mongoose-wrapper-simple": "file:../mongoose-wrapper-simple"
}
}cd other-project
npm installThe package ships only its compiled output (main / types / exports all point into
dist/, and dist/ is git-ignored). Its prepare script builds dist/ automatically
whenever the package is installed as a file: (or git) dependency, so npm install is
all you need.
Troubleshooting — if you see
Cannot find module 'mongoose-wrapper-simple' or its corresponding type declarations, the compileddist/output is missing (e.g. a stale checkout). Re-runnpm installin the consuming project (this triggersprepare), or manually runnpm run buildinsidemongoose-wrapper-simple.
Quick Start
import { Schema } from 'mongoose';
import {
mongooseDefaultPlugins,
mongooseReferencePlugins,
mongooseDefaultSchemaOptions,
ENUM_PAGING_MODE,
} from 'mongoose-wrapper-simple';
// apply ALL default behaviors: soft-delete pre-action + pagination + default schema
const userSchema = new Schema({ name: String }, mongooseDefaultSchemaOptions);
mongooseDefaultPlugins(userSchema);
// reference / sub-document schema: only add the default schema fields
const addressSchema = new Schema({ street: String }, mongooseDefaultSchemaOptions);
mongooseReferencePlugins(addressSchema);Features
mongooseDefaultPlugins(schema)— apply all default behaviors in one call:- pre-action soft delete (
mongoose-pre-action) - pagination (
mongoose-pagination) - default schema (
mongoose-default-schema)
- pre-action soft delete (
mongooseReferencePlugins(schema)— add only the default schema fields (for reference / sub-document schemas)mongooseDefaultSchemaOptions—SchemaOptionsthat mapcreatedAt/updatedAttimestamps tocreatedUtcDate/updatedUtcDateENUM_PAGING_MODE—'nopaging' | 'page' | 'next' | 'all'
Default schema fields
Added by both plugins (all fields are select: false):
| field | type | description |
| ---------------- | ------- | ------------------------------------- |
| createdUtcDate | Date | auto-set on create |
| createdBy | String | |
| updatedUtcDate | Date | auto-set on update (timestamps) |
| updatedBy | String | |
| deleted | Boolean | soft-delete flag |
| deletedBy | String | |
| deletedUtcDate | Date | stamped automatically on soft delete |
| __v | Number | mongoose version key (hidden) |
Soft delete behavior (pre-action hooks)
count,countDocuments,estimatedDocumentCount,find,findOne,distinct→ automatically filterdeleted: { $ne: true }findOneAndUpdate,updateOne,updateMany,findOneAndReplace,replaceOne→ filter non-deleted records; whendeleted: trueis set,deletedUtcDateis stamped automaticallydeleteOne,deleteMany,findOneAndDelete,findOneAndRemove→ blocked — soft-delete the record instead of removing it
// soft delete (allowed)
await userModel.updateOne({ _id }, { deleted: true });
// hard delete (blocked - throws)
await userModel.deleteOne({ _id });Pagination
Adds the mongoose-paginate-v2 plugin and a static findWithPaging(query, pagingOptions, queryOptions).
const result = await userModel.findWithPaging(
{ name: /^A/ }, // query
{
pagingMode: ENUM_PAGING_MODE.page,
page: 1,
limit: 10,
sort: { createdUtcDate: -1 },
},
// queryOptions: e.g. { select: 'name email' }
);
// result = {
// results: [...],
// paging: {
// pagingMode: 'page',
// limit: 10,
// currentCount: 10,
// currentPage: 1,
// totalPage: 3,
// totalCount: 25,
// hasPrevPage: false,
// hasNextPage: true,
// prevPage: null,
// nextPage: 2,
// }
// }findWithPaging always filters out soft-deleted records (deleted: { $ne: true }).
Paging modes
| pagingMode | behavior |
| ---------------- | ----------------------------------------------------------------- |
| nopaging | first page only, no page/total metadata |
| page | classic page/limit with total counts and prev/next navigation |
| next | next-token (cursor) paging using a hex-encoded token |
| all | all matching records (capped at 500) |
Every mode returns a { results, paging } shape, which pairs directly with express-wrapper-simple's res.sendSuccess (it detects the { results, paging } shape automatically).
References
ENUM_PAGING_MODEnopaging— no paging, first page onlypage— offset / page-based pagingnext— next-token (cursor) pagingall— all matching records (max 500)
Development / Publishing
npm install # install dev dependencies (runs prepare -> builds dist/)
npm run build # clean, compile dist/, minify (gulp)
npm test # type-check a consumer project against dist/ (no type errors)
npm pack # create the publishable tarball (runs prepare first)
npm publish # publish to npm registry (runs prepare first)prepareruns on localnpm installand onfile:/ git dependency installs, sodist/is always built before the package is consumed or published.- Only the contents of
dist/(plusREADME.md,LICENSE,package.json) are shipped; the source, tests and build tooling are excluded via thefilesfield. mongooseis a peer dependency so consumers never end up with two Mongoose instances (which would otherwise cause schema / model identity mismatches).- The published
.d.tsonly referencesmongoosetypes, so consumers do not need@types/mongoose-paginate-v2,@types/nodeor any other@types/*package.
