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:
33
src/runtime/server/services/discriminator.ts
Normal file
33
src/runtime/server/services/discriminator.ts
Normal 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)
|
||||||
|
}
|
||||||
@ -1,2 +1,3 @@
|
|||||||
export { defineMongooseConnection } from './connection'
|
export { defineMongooseConnection } from './connection'
|
||||||
export { defineMongooseModel } from './model'
|
export { defineMongooseModel } from './model'
|
||||||
|
export { defineMongooseDiscriminatorModel } from './discriminator'
|
||||||
|
|||||||
Reference in New Issue
Block a user