Closed adrianwiechec-at-optilyz closed 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.
Thanks!
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?