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-model-class

v3.0.0

Published

Define Mongoose models using ES6/TypeScript classes with lifecycle hooks, static methods, and virtuals

Readme

mongoose-model-class

Define Mongoose models using ES6/TypeScript classes with lifecycle hooks, static methods, instance methods, and virtual properties.

Installation

npm install mongoose-model-class mongoose
# or
pnpm add mongoose-model-class mongoose

Usage

import { MongooseModelClass } from 'mongoose-model-class';
import type { Document, HydratedDocument } from 'mongoose';

interface UserDocument extends Document {
  name: string;
  email: string;
  password: string;
  createdAt: Date;
}

class User extends MongooseModelClass<UserDocument> {
  // Required: Define your schema
  schema() {
    return {
      name: { type: String, required: true },
      email: { type: String, required: true, unique: true },
      password: { type: String, required: true },
    };
  }

  // Optional: Schema options
  options() {
    return { timestamps: true };
  }

  // Optional: Configure schema (add indexes, plugins, etc.)
  config(schema) {
    schema.index({ email: 1 });
  }

  // Instance method
  getDisplayName() {
    return this.name.toUpperCase();
  }

  // Static method
  static async findByEmail(email: string) {
    return this.findOne({ email });
  }

  // Virtual property (getter)
  get initials() {
    return this.name.split(' ').map(n => n[0]).join('');
  }

  // Lifecycle hook: before save
  async beforeSave(doc: HydratedDocument<UserDocument>) {
    if (doc.isModified('password')) {
      doc.password = await hashPassword(doc.password);
    }
  }

  // Lifecycle hook: after save
  async afterSave(doc: HydratedDocument<UserDocument>) {
    console.log(`User ${doc.name} saved`);
  }

  // Lifecycle hook: before delete
  async beforeDelete(doc: HydratedDocument<UserDocument>) {
    console.log(`Deleting user ${doc.name}`);
  }
}

export default User;

Building the Model

import mongoose from 'mongoose';
import User from './models/User';

const connection = await mongoose.createConnection('mongodb://localhost/mydb');
const userModel = new User();
const UserModel = userModel.build(connection, 'User');

// Now use it like a regular Mongoose model
const user = await UserModel.create({
  name: 'John Doe',
  email: '[email protected]',
  password: 'secret123',
});

// Static methods work
const found = await UserModel.findByEmail('[email protected]');

// Instance methods work
console.log(user.getDisplayName()); // 'JOHN DOE'

// Virtuals work
console.log(user.initials); // 'JD'

API

Class Methods

| Method | Description | |--------|-------------| | schema() | Required. Returns schema definition object | | options() | Returns schema options (timestamps, etc.) | | config(schema) | Configure schema after creation | | build(connection, name) | Build and return mongoose model |

Lifecycle Hooks

| Hook | Description | |------|-------------| | beforeSave(doc) | Called before document is saved | | afterSave(doc) | Called after document is saved | | beforeDelete(doc) | Called before document is deleted | | afterDelete(doc) | Called after document is deleted |

Static Properties

| Property | Description | |----------|-------------| | MongooseModelClass.adapter | Mongoose instance | | MongooseModelClass.Schema | Schema class | | MongooseModelClass.types | Schema.Types (ObjectId, etc.) | | MongooseModelClass.parseObjectId(id) | Parse string to ObjectId |

Migration from v2.x

Breaking Changes

  1. Node.js 18+ required
  2. ES Modules - Use import instead of require
  3. Mongoose 6+ - remove() hooks replaced with deleteOne()
  4. Renamed hooks - beforeRemove/afterRemovebeforeDelete/afterDelete

Migration Steps

// Before (v2.x)
const MongooseModelClass = require('mongoose-model-class');

class User extends MongooseModelClass {
  beforeRemove(doc, next) {
    // cleanup
    next();
  }
}

// After (v3.x)
import { MongooseModelClass } from 'mongoose-model-class';

class User extends MongooseModelClass<UserDocument> {
  async beforeDelete(doc) {
    // cleanup (no need for next())
  }
}

License

Apache-2.0