1.4.0 • Published 1 year ago

mongo-class-models v1.4.0

Weekly downloads
-
License
ISC
Repository
github
Last release
1 year ago

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.

1.4.0

1 year ago

1.3.1

1 year ago

1.3.0

1 year ago

1.2.0

1 year ago

1.1.1

1 year ago

1.1.0

1 year ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago

0.0.11

2 years ago

0.0.10

2 years ago

0.0.9

2 years ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago