Hello There,
I really like this library and as a big user of zod, I was quite happy when I found a type safe way to deal with mongoose, so thank you for making it.
That being said, I have ran into a problem which I can not for the life of me figure out how to get around, that is if I try to use unions for my return objects the validation seems to think the field is empty.
initial schema
export const IssueSchema = z.object({
id: IdentifierSchema,
title: z.string(),
type: z.nativeEnum(IssueType),
content: z.string(),
user: z.string(),
metadata: MediaProviderUnionSchema,
});
export type Issue = z.infer<typeof IssueSchema>;
This schema is acts like a base schema, that is later extended by my DTO schema that is returned from the database, you'll notice that this schema has user
set to just a string (this represents the reference from the db).
export const IssueDTOSchema = IssueSchema.extend({
user: z.union([UserSchema, z.string()]),
});
export type IssueDTO = z.infer<typeof IssueDTOSchema>;
//
export const IssueDTOMongoSchema = IssueDTOSchema
.mongoose({
schemaOptions: {
collection: 'issues',
virtuals: {
user: {
options: {
ref: 'user',
localField: 'user',
foreignField: 'id',
}
}
}
},
typeOptions: {
user: {
ref: 'user',
}
}
});
export type IssueDTOMongo = z.infer<typeof IssueDTOMongoSchema>;
The reason for extending was to get around the circular dependency issue, which I solved in this way by just extending it and overriding the initial field with a union, so the user schema can be be returned if it's populate method is used when pulling the data from the database, else it will just return the string as it would normally.
The problem is that no matter the combination, the validation errors out thinking the user field is undefined? Not sure if I have missed something in the documentation, or something long those lines.
{
"code": "invalid_union",
"unionErrors": [
{
"issues": [
{
"code": "invalid_type",
"expected": "object",
"received": "undefined",
"path": [
"user"
],
"message": "Required"
}
],
"name": "ZodError"
},
{
"issues": [
{
"code": "invalid_type",
"expected": "string",
"received": "undefined",
"path": [
"user"
],
"message": "Required"
}
],
"name": "ZodError"
}
],
"path": [
"user"
],
"message": "Invalid input"
}
]
Here is also the seed data I am using to test with.
const IssueData: Issue[] = [
{
id: "8I6u5mg53wd0YXEHtCewb",
title: "Problem with playing content",
type: IssueType.BadVideo,
content: "I am unable to play movie",
user: 'H9ITrq4x2GQ2E_-XKUlIM',
metadata: {
tmdbId: 615656,
}
}
];
Any help with this is appreciated. Thanks.