mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

Optional objects

Open leosilberg opened this issue 11 months ago • 3 comments

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()

leosilberg avatar Jan 14 '25 19:01 leosilberg

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.

brense avatar May 21 '25 07:05 brense

same

Goldziher avatar May 30 '25 22:05 Goldziher

also got this issue, would be nice if this gets solved soon

EDIT: seems fixed, someone going to build a new version on main?

Lastone17 avatar Sep 25 '25 05:09 Lastone17