arashsheyda / nuxt-mongoose

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

Ability to define hooks #11

Closed sarmancoderr closed 1 year ago

sarmancoderr commented 1 year 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 1 year ago

@sarmancoderr great idea. thanks

arashsheyda commented 1 year 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.