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

refs? #5

Closed adrianwiechec-at-optilyz closed 1 year ago

adrianwiechec-at-optilyz commented 1 year ago

A question: how do you define refs (https://mongoosejs.com/docs/populate.html) with mongoose-zod? I know I can set the type of the relationship field to mongooseZodCustomType("ObjectId"), but how do I specify the related model?

andreww2012 commented 1 year ago

You can define a ref using type options, in two ways:

import {mongooseZodCustomType, toMongooseSchema} from 'mongoose-zod';
import {z} from 'zod';

const UserZod = z.object({
  // Option 1: use `mongooseTypeOptions()`
  friends: mongooseZodCustomType('ObjectId').mongooseTypeOptions({
    ref: 'User',
  }),
});

const UserSchema = toMongooseSchema(
  UserZod.mongoose({
    // Option 2: use `typeOptions: { ... }
    typeOptions: {
      friends: {ref: 'User'},
    },
  }),
);

export const User = M.model('User', UserSchema);

When it comes to adding proper types for fields with references, I don't think it is even possible. You need to handle types yourself, unfortunately.

adrianwiechec-at-optilyz commented 1 year ago

Thanks!