arashsheyda / nuxt-mongoose

A Nuxt module for simplifying the use of Mongoose in your project.
https://docs.arashsheyda.me/nuxt-mongoose
69 stars 11 forks source link

Ability to define hooks #11

Closed sarmancoderr closed 11 months ago

sarmancoderr commented 11 months ago
import { defineMongooseModel } from "#nuxt/mongoose";

export const User = defineMongooseModel({
    name: 'users',
    schema: {
        user: {type: 'String'},
        password: {type: 'String'},
    },
    options: {
        methods: {

        }
    }
})

Here I would like to have a way in wich i could have the ability to define a pre save hook to crypt the password, please consider this

arashsheyda commented 11 months ago

@sarmancoderr great idea. thanks

arashsheyda commented 11 months ago

implented in this commit

we can use it like

import { defineMongooseModel } from '#nuxt/mongoose'

export const UserSchema = defineMongooseModel({
  name: 'User',
  schema: {
    email: {
      type: 'string',
      required: true,
      unique: false,
    },
    password: {
      type: 'string',
      required: true,
    },
  },
  hooks(schema) {
    schema.pre('save', function (this, next) {
      this.password = `hash.${this.password}}`
      next()
    })
  },
})

thanks for the idea again.