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
49 stars 7 forks source link

Add example for models with relationships or embedded objects (subdocuments) #12

Closed bennidi closed 7 months ago

bennidi commented 1 year ago

I think the title says it all. Since I am new to mongoose and zod I am struggling with how to build a model that has embedded documents as well as relationships. Maybe I am just being a bit stupid?

I assume you have some code samples at hand for this. Maybe you can share those?

angelhdzmultimedia commented 7 months ago

As the OP, I need help working with relations.

I've navigated almost every option in the zod/mongoose schema, and can't see how to set the ref.

In Prisma is very easy to do, but I no longer want to work with Prisma because want to do everything with TypeScript code (also don't want to execute prisma generate every time I make a change in the schema...)

I have a UserValidationSchema (zod) with a property profile which is a UserProfileValidationSchema (zod). When creating a user in users collection, it should create a profile in user-profiles collection, and when retrieving a user from users, it should bring the corresponding profile from user-profiles.

I will appreciate a lot any info. Thank you!

Edit I found it!!! 🔥🤯 image

andreww2012 commented 7 months ago

Hello, please see https://github.com/andreww2012/mongoose-zod/issues/5#issuecomment-1518685724 Defining relationships is fully handled by mongoose. Remember that mongoose-zod is just a convenient constructor of mongoose schemas, and if you can't find a feature that is supported by mongoose-zod, you should go down to mongoose level. Perhaps explicitly mentioning handling references in the documentation is a good idea. 👍