mongoose
mongoose copied to clipboard
Optional objects
I came across this case where nested zod objects marked as optional aren't being converted to required false in the mongoose Schema
const addressSchema = z.object({
city: z.string(),
zip: z.string(),
});
const userSchema = z.object({
name: z.string(),
email: z.string().email(),
address: addressSchema.optional(),
});
const schema = zodSchema(userSchema);
console.log(schema.obj);
console.log(userSchema.safeParse({ name: "User", email: "[email protected]" }));
Output
{
name: {
type: [class String],
default: undefined,
required: true,
minLength: undefined,
maxLength: undefined,
unique: false,
},
email: {
type: [class String],
default: undefined,
required: true,
minLength: undefined,
maxLength: undefined,
unique: false,
},
address: {
city: {
type: [class String],
default: undefined,
required: true,
minLength: undefined,
maxLength: undefined,
unique: false,
},
zip: {
type: [class String],
default: undefined,
required: true,
minLength: undefined,
maxLength: undefined,
unique: false,
},
},
}
{
success: true,
data: {
name: "User",
email: "[email protected]",
},
}
I think a solution would be that the parseObject function should return { type : object , required ....} if it's parsing a nested z.object()
We are also running into this same issue:
export const configSchema = z.object({
events: z
.object({
useEvents: z.boolean().default(false),
queueName: z.string(),
})
.optional(),
})
Even though the events property is optional, when we try to create a document with mongoose, it complains that events.queueName is required.
same
also got this issue, would be nice if this gets solved soon
EDIT: seems fixed, someone going to build a new version on main?