npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

mongoose-crud-service

v1.4.16

Published

A customizable service that implements top level CRUD operations as well as one-level nested CRUD operations

Readme

Generic Mongoose Crud Service

A customizable service that implements top level CRUD operations as well as one-level nested CRUD operations.

How to install

npm install --save mongoose-crud-service

## How to use it

The service can be used in two different ways.

Class inheritance (Recommended)

class UsersService extends GenericMongooseCrudService<ITestData> {
  eventsCreate = 'FOO';
  model = UserModel;
}

Instance initiation

const service = new GenericMongooseCrudService<ITestData>({
  model,
  modelName: MODEL_NAME
});

### Options

export interface IGenericMongooseCrudServiceOptions<T extends IMongoDocument> {
  eventsCreate?: string;
  eventsDelete?: string;
  eventsPatch?: string;
  model?: Model<T>;
  modelName?: string;
}

NestJS Examples

@Injectable()
export class UsersService extends GenericMongooseCrudService<IUser> {
  eventEmitter: EventEmitter = new EventEmitter();
  @InjectModel(USER_MODEL_NAME) private readonly userModel: Model<IUserModel>;
}

### Timestamped

The service automatically adds timestamps for the write operations. It also stores a user attribute, which can of type any.

  • Create --> createdAt and createdBy
  • Update --> updatedAt and updatedBy

Schemas and interfaces

In the package we can find the timestampedSchemaDefinition which we can used to add the timestamp properties to the schemas

const userSchemaDefinition: SchemaDefinition = {
  username: String
};
const schemaDefinition: SchemaDefinition = Object.assign<
  SchemaDefinition,
  SchemaDefinition
>(timestampedSchemaDefinition, userSchemaDefinition);

We also find several interfaces, but the most important ones are IModelInstance and IMongoDocument. The first one is the interface that are objects must implement, the second one is used internally to add the Mongoose Document properties.

interface ITestData extends IModelInstance {
  subs: ITestSubData[];
  value: string;
}

interface ITestDataModel extends ITestData, IMongoDocument {
  subs: mongoose.Types.DocumentArray<ITestSubDataModel>;
}

const schemaDefinition: mongoose.SchemaDefinition = Object.assign<
  mongoose.SchemaDefinition,
  mongoose.SchemaDefinition,
  mongoose.SchemaDefinition
>({}, timestampedSchemaDefinition, {
  value: { type: String },
  subs: [subSchemaDefinition]
});

model = mongoose.model(MODEL_NAME, new mongoose.Schema(schemaDefinition));
service = new GenericMongooseCrudService<ITestData, ITestDataModel>({
  model,
  modelName: MODEL_NAME
});

Soft Delete

This service implements soft delete, which is a common feature requested in many projects. When applying one of the soft delete methods, the property deleted will be set to true, and will not be found by any of the other methods, except the list methods if explictly search for objects with { deleted : true } filter. It also adds the deletedAt and deletedBy properties.

### Subdocuments CRUD

The service supports the same operations of top level documents for subdocuments in arrays. Thi feature is still somehow experimental but it is pretty usable.

All subdocument operations are considered update operations on the parent document

Extension through events

Each of the write operations has an event that can be listened to in order to react o extend this operations. As an example, you could want to log each time an object is created. This is for event-based development. The name of the events can be customizable. The event emitter can be accessed through the events property. The event receives the modified/created document.

usersService.eventEmitter.on(eventName, async (data: IUserModel) => {
  // Do something
});

Methods

The service has methods for documents and first-level subdocuments (Deeply nested subdocuments is not supported). Most methods are aliases of other methods, like the ById kind that will call the basic method with an objectId in the query.

export declare class GenericMongooseCrudService<
  T extends IModelInstance,
  M extends T & IMongoDocument
> {
  addSubdocument<Subdocument extends IModelInstance>(
    parentId: string,
    subdocumentField: string,
    subdocument: any,
    user: any
  ): Promise<Subdocument>;
  count(filter?: IDynamicObject): Promise<number>;
  countSubdocuments(
    parentId: string,
    subdocumentField: string,
    filter?: IDynamicObject
  ): Promise<number>;
  create(data: Partial<T>, user: any): Promise<M>;
  getById(_id: string, projection?: string): Promise<M>;
  getSubdocument<Subdocument extends IModelInstance>(
    parentId: string,
    subdocumentField: string,
    filter?: IDynamicObject
  ): Promise<Subdocument & IMongoDocument>;
  getSubdocumentById<Subdocument extends IModelInstance>(
    parentId: string,
    subdocumentField: string,
    subdocumentId: string
  ): Promise<Subdocument & IMongoDocument>;
  hardDelete(_id: string): Promise<M>;
  hardDeleteSubdocument(
    parentId: string,
    subdocumentField: string,
    subdocumentId: string,
    user: any
  ): Promise<M>;
  list(
    filter?: IDynamicObject,
    limit?: number,
    skip?: number,
    projection?: string,
    sort?: ISortOptions
  ): Promise<Array<M>>;
  listSubdocuments<Subdocument extends IModelInstance>(
    parentId: string,
    subdocumentField: string,
    filter?: IDynamicObject,
    limit?: number,
    skip?: number,
    sort?: ISortOptions
  ): Promise<Array<Subdocument & IMongoDocument>>;
  patch(filter: IDynamicObject, update: IDynamicObject, user: any): Promise<M>;
  patchById(_id: string, update: any, user: any): Promise<M>;
  patchSubdocument<Subdocument extends IModelInstance>(
    parentId: string,
    subdocumentField: string,
    filter: IDynamicObject,
    update: any,
    user: any
  ): Promise<Subdocument & IMongoDocument>;
  patchSubdocumentById<Subdocument extends IModelInstance>(
    parentId: string,
    subdocumentField: string,
    subdocumentId: string,
    update: any,
    user: any
  ): Promise<Subdocument & IMongoDocument>;
  softDelete(_id: string, user: any): Promise<M>;
  softDeleteSubdocument<Subdocument extends IModelInstance>(
    parentId: string,
    subdocumentField: string,
    subdocumentId: string,
    user: any
  ): Promise<Subdocument & IMongoDocument>;
  update(filter: IDynamicObject, update: IDynamicObject, user: any): Promise<M>;
  updateById(_id: string, update: IDynamicObject, user: any): Promise<M>;
}