mongo-class-models
v1.4.0
Published
Easy mongoose class models and repos
Downloads
4
Maintainers
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
- Create
repos/
folder in your app folder - Create Repo file (Recommended use this name pattern -
{ModelName}Repo.(ts|js)
)
Setup Repo
Configuring model interface
- Create new interface (Recommended name -
{ModelName}Model
) - 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[]
}
- 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
}
- 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")
})
);
- 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 useSubSchema
. 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
}
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)
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>
- FinalModelDBHelper.FinalModel.DataType<ModelType>
- all fields without _idDBHelper.FinalModel.FullDataType<ModelType>
- all fields with _idDBHelper.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 ModelmodelKeys
- 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 reposcreateModel
(modelData) - create new model in collection. Returns FinalModelfindOne
,findMany
,findById
- exact same as in mongoose but returns FinalModel andfind
changed tofindMany
deleteOne
,deleteMany
,updateOne
,updateMany
- exact same as in mongoosebulkSave
,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 idsyncSave
,save
- save data (Recommended use asyncsave
)delete
- delete model from dbpartialDataUpdate
- (unsafe) way to update data takes any object and updates same fieldsupdate
- 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.