feat: mongoose schema hooks

This commit is contained in:
Arash Sheyda
2023-07-09 13:25:38 +03:00
parent 5a43ebe06f
commit d92a58b2ad
3 changed files with 30 additions and 7 deletions

View File

@ -7,10 +7,20 @@ export const UserSchema = defineMongooseModel({
type: 'string', type: 'string',
required: true, required: true,
}, },
slug: { email: {
type: 'string',
required: true,
unique: false,
},
password: {
type: 'string', type: 'string',
required: true, required: true,
unique: true,
}, },
}, },
hooks(schema) {
schema.pre('save', function (this, next) {
this.password = `hash.${this.password}.${Math.random()}`
next()
})
},
}) })

View File

@ -18,7 +18,17 @@ export async function defineMongooseConnection({ uri, options }: { uri?: string;
} }
} }
export function defineMongooseModel<T>(nameOrOptions: string | { name: string; schema: SchemaDefinition; options?: SchemaOptions }, schema?: SchemaDefinition, options?: SchemaOptions): Model<T> { export function defineMongooseModel<T>(
nameOrOptions: string | {
name: string
schema: SchemaDefinition
options?: SchemaOptions
hooks?: (schema: mongoose.Schema<T>) => void
},
schema?: SchemaDefinition,
options?: SchemaOptions,
hooks?: (schema: mongoose.Schema<T>) => void,
): Model<T> {
let name: string let name: string
if (typeof nameOrOptions === 'string') { if (typeof nameOrOptions === 'string') {
name = nameOrOptions name = nameOrOptions
@ -27,10 +37,13 @@ export function defineMongooseModel<T>(nameOrOptions: string | { name: string; s
name = nameOrOptions.name name = nameOrOptions.name
schema = nameOrOptions.schema schema = nameOrOptions.schema
options = nameOrOptions.options options = nameOrOptions.options
hooks = nameOrOptions.hooks
} }
const newSchema = new mongoose.Schema<T>({ const newSchema = new mongoose.Schema<T>(schema, options as any)
...schema,
}, { ...options }) if (hooks)
hooks(newSchema)
return mongoose.model<T>(name, newSchema) return mongoose.model<T>(name, newSchema)
} }

View File

@ -1,3 +1,3 @@
{ {
"extends": "./client/.nuxt/tsconfig.json" "extends": "./playground/.nuxt/tsconfig.json"
} }