feat: add discriminator helper (#47)

* add discriminator.ts helper

Allow extension and inheritance of base models with discriminator models.

* Update index.ts

* fix typo in index.ts
This commit is contained in:
Justin Bellero
2024-04-24 17:23:47 -04:00
committed by GitHub
parent 3ef0d69ded
commit 6b4d1ed0ae
2 changed files with 34 additions and 0 deletions

View File

@ -0,0 +1,33 @@
import type { Model, SchemaDefinition, SchemaOptions } from 'mongoose'
import mongoose from 'mongoose'
export function defineMongooseDiscriminatorModel<T>(
nameOrOptions: string | {
name: string;
baseModel: Model<T>;
schema: SchemaDefinition<T>;
options?: SchemaOptions;
hooks?: (schema: mongoose.Schema<T>) => void;
},
baseModel?: Model<T>,
schema?: SchemaDefinition<T>,
options?: SchemaOptions,
hooks?: (schema: mongoose.Schema<T>) => void,
): Model<T> {
let name: string
if (typeof nameOrOptions === 'string') { name = nameOrOptions }
else {
name = nameOrOptions.name
baseModel = nameOrOptions.baseModel
schema = nameOrOptions.schema
options = nameOrOptions.options
hooks = nameOrOptions.hooks
}
const newSchema = new mongoose.Schema<T>(schema, options as any)
if (hooks)
hooks(newSchema)
return baseModel!.discriminator<T>(name, newSchema)
}

View File

@ -1,2 +1,3 @@
export { defineMongooseConnection } from './connection'
export { defineMongooseModel } from './model'
export { defineMongooseDiscriminatorModel } from './discriminator'