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 🙏

© 2024 – Pkg Stats / Ryan Hefner

mongo-class-models

v1.4.0

Published

Easy mongoose class models and repos

Downloads

4

Readme

MongoDB Class Models

Simple package for fast work with mongoose package and typescript + OOP

  • OOP pattern
  • Repos and Models
  • Easy to use

Instalation

npm

npm i mongo-class-models

Usage

Creating Repos

  1. Create repos/ folder in your app folder
  2. Create Repo file (Recommended use this name pattern - {ModelName}Repo.(ts|js))

Setup Repo

Configuring model interface

  1. Create new interface (Recommended name - {ModelName}Model)
  2. Add extensions to your interface from DBHelper.ModelExtension (It should extends DBHelper.ModelExtension.ID. Others extensions are optional). Example:
interface ArticleModel extends
    //ID is required
    DBHelper.ModelExtension.ID.Default,
    //Timestamps are optional
    DBHelper.ModelExtension.Timestamps<"snake_case">
{
    name: string,
    tags: string[]
}
  1. Create Repo class. It should extend DBHelper.Repo.RootRepo abstract class (Recommended name - {ModelName}Repo). Example:
class ArticleRepo extends DBHelper.Repo.RootRepo<ArticleModel> {
    //Here you can create custom properties and methods and use it later
}
  1. Create exported instance of your Repo class (Recommended name - {modelName}Repo). Example:
export const articleRepo = new ArticleRepo(
    "Article", //Model Name
    "atricles", //Collection Name
    DBHelper.Repo.init({ //Init Options and Schema definition
        name: DBHelper.MV({type: "String", required: true}),
        tags: [DBHelper.MV({type: "String"})]
    },{ //Schema options
        ...DBHelper.RepoOptions.timestamps("snake_case")
    })
);
  1. Use Repo in your app. Example:
let article = await articleRepo.createModel({
    name: "First Article",
    tags: ["cool", "fast"]
})

let articles = await articleRepo.findMany({});

console.log(articles);

Docs

DBHelper is main namespace in this package. All package functional gets from it

DBHelper.ModelExtension {#model-extension}

Extensions for model interface

ModelInterface Example: {#model-interface}

interface SectionModel extends
    DBHelper.ModelExtension.ID.Default,
    DBHelper.ModelExtension.Timestamps<"snake_case">
{
    name: string,
    tags: string[]
}

DBHelper.ModelExtension.ID {#model-extension__id}

  • DBHelper.ModelExtension.ID.Default - mongoose.Types.ObjectId (default mongodb model id)

  • DBHelper.ModelExtension.ID.String

  • DBHelper.ModelExtension.ID.Number


DBHelper.ModelExtension.Timestamps<TimestampsStyle> {#timestamps-style}

type TimestampsStyle = "camelCase" | "snake_case";

DBHelper.Model {#model}

Additional types for ModelInterface

  • DBHelper.Model.Ref - Reference to another Repo. Example:
interface IArticle extends
    DBHelper.ModelExtension.ID.Default,
    DBHelper.ModelExtension.Timestamps<"snake_case">
{
    name: string,
    desc: string,
    main_section: DBHelper.Model.Ref<SectionModel>,
}
  • DBHelper.Model.SubSchema - Nested Object. If you want to use nested object you should use SubSchema. Example:
interface IArticle extends
    DBHelper.ModelExtension.ID.Default,
    DBHelper.ModelExtension.Timestamps<"snake_case">
{
    name: string,
    desc: string,
    stats: DBHelper.Model.SubSchema<{
        views: number,
        shows: number
    }>
}

DBHelper.Repo {#repo}

Everything to initialize the Repo

  • DBHelper.Repo.RootRepo<ModelType> - RootRepo. Your Repos should extends it.

Usage Example:

class ArticleRepo extends DBHelper.Repo.RootRepo<IArticle> {
    //Here you can create custom properties and methods and use it later
}

More About It


  • DBHelper.Repo.init(definition,options) - Initialize PreSchema for RootRepo {#preschema-init}

@definition - Object of model keys value's type

@options - Simple Mongoose Schema Options

Usage Example:

const sectionRepo = new SectionRepo(
    "Section",
    "sections",
    DBHelper.Repo.init({
        name: DBHelper.MV({type: String, required: true}),
        tags: [DBHelper.MV({type: String})]
    })
);

  • DBHelper.Repo.initSubSchema(definition,options) - Initialize SubPreSchema for PreSchema

@definition - Object of model keys value's type

@options - Simple Mongoose Schema Options

Usage Example:

export const articleRepo = new ArticleRepo(
    "Article",
    "atricles",
    DBHelper.Repo.init({
        name: DBHelper.MV({type: "String", required: true}),
        desc: DBHelper.MV({type: "String", required: true}),
        stats: DBHelper.Repo.initSubSchema<IArticle["stats"]>({
            views: DBHelper.MV({type: Number, required: true}),
            shows: DBHelper.MV({type: Number, required: true})
        })
    })
);

  • DBHelper.Repo.mongooseValue(valueType) - Value type constructor {#mongoose-value}

@valueType - Simple Mongoose SchemaTypes

DBHelper.MV({type: Number}) //It will be in your schema - {type: Number}
DBHelper.MV({type: Number, required: true}) // {type: Number, required: true}
DBHelper.MV({type: String}) // {type: String}
DBHelper.MV({type: Boolean, required: true}) // {type: Boolean, required: true}
DBHelper.MV({type: mongoose.Types.ObjectId, required: true, unique: true}) // {type: mongoose.Types.ObjectId, required: true, unique: true}

DBHelper.MV(valueType) - mongooseValue


DBHelper.RepoOptions

Option shortcuts

DBHelper.RepoOptions.timestamps(timestampsStyle)

timestampsStyle

Usage Example:

export const sectionRepo = new SectionRepo(
    "Section",
    "sections",
    DBHelper.Repo.init({
        name: DBHelper.MV({type: String, required: true}),
        tags: [DBHelper.MV({type: String})]
    },{
        ...DBHelper.RepoOptions.timestamps("snake_case")
    })
);

DBHelper.FinalModel {#final-model}

FinalModel Types

  • DBHelper.FinalModel.FinalModel<ModelType> - FinalModel

  • DBHelper.FinalModel.DataType<ModelType> - all fields without _id

  • DBHelper.FinalModel.FullDataType<ModelType> - all fields with _id

  • DBHelper.FinalModel.PlainModel<ModelType> - ModelDataType used for creating new model


Types, Classes, Interfaces

abstract class RootRepo {#root-repo}

  • constructor( modelName: string, collectionName: string, initSchema, modelOptions?: mongoose.CompileModelOptions ){}
  • Model - Mongoose Model
  • modelKeys - all first level keys in model (with _id)
  • changeableModelKeys - all first level keys in model (without _id)
  • getRefSchemaType(fieldOptions: mongoose.SchemaDefinitionProperty<ModelType["_id"]> & object = {}) - Ref type for others repos
  • createModel(modelData) - create new model in collection. Returns FinalModel
  • findOne, findMany, findById - exact same as in mongoose but returns FinalModel and find changed to findMany
  • deleteOne, deleteMany, updateOne, updateMany - exact same as in mongoose
  • bulkSave, bulkWrite - exact same as in mongoose but requires finalModels in parameters

class FinalModel<ModelType> {#final-model}

  • constructor( dbModel: mongoose.HydratedDocument<ModelType>, repo: RootRepo<ModelType> ){}
  • dbModel - mongoose.HydratedDocument<ModelType>;
  • Repo: RootRepo<ModelType>;
  • data - get, set model data (except _id)
  • id - readonly model id
  • syncSave, save - save data (Recommended use async save)
  • delete - delete model from db
  • partialDataUpdate - (unsafe) way to update data takes any object and updates same fields
  • update - copy data and paste to private dbModel (without saving in DB)
  • restore - copy private dbModel data and paste to data

License

Allowed to use in (private|commercial) projects.