andreww2012 / mongoose-zod

A library which allows to author mongoose ("a MongoDB object modeling tool") schemas using zod ("a TypeScript-first schema declaration and validation library").
MIT License
48 stars 7 forks source link

[question] Missing pick, extend, and omit #15

Closed angelhdzmultimedia closed 6 months ago

angelhdzmultimedia commented 6 months ago

Hello!

In a normal z.object, we can use .pick, .extend, and .omit. I usually use const LoginSchema = UserSchema.pick({email: true, password: true}) and const RegisterSchema = UserSchema.omit({id: true}).

But after using z from mongoose-zod, I can't do that anymore.

Any info will be appreciated.

angelhdzmultimedia commented 6 months ago

Solved?

I think I may have solved it.

export const UserValidationSchema = z.object({
  id: z.string().mongooseTypeOptions({auto: true, type: 'String', }),
  email: z.string().email(),
  uuid: z.string(),
  password: z.string().min(6),
  profile: UserProfileValidationSchema.mongooseTypeOptions({
    ref: 'UserProfile',
    type: mongoose.Schema.Types.ObjectId
  })
})

export type UserData = z.infer<typeof UserValidationSchema>

export const UserModelSchema = toMongooseSchema(UserValidationSchema.mongoose({
  schemaOptions: {
   collection: 'users',

   query: {

   }
  }
}))

Moved the .mongoose chained method to the toMongooseSchema function call, and left the UserValidationSchema alone, now I got the .pick method back!!!

import { UserValidationSchema } from '~/user/user.schema'

const LoginValidationSchema = UserValidationSchema.pick({
  email: true,
  password: true,
})
andreww2012 commented 6 months ago

Hello, this is a correct approach indeed. After calling .mongoose() on a zod schema you can't use zod methods anymore because it returns a non-zod object.