Zod 2 beta 5: parse() adds optional fields with 'undefined' as a value
See original GitHub issueHi @vriad,
I’ve upgraded to Zod 2 beta and it works cool.
The first bug I’ve met now, is that if you send an object without certain optional fields, .parse()
adds them with undefined value.
For instance, my schema looks like that (simplified):
export const SNamedEntity = z.object({
_id: string().refine(validateUUID),
name: z.string().max(100),
createdAt: string().refine(validateDateString).optional(),
updatedAt: string().refine(validateDateString).optional(),
isActive: boolean().optional(),
});
And the object I send to it has only _id
and name
. However, when I set a breakpoint after I .parse()
this object with the with the above schema, I see that all of the optional fields are present there now:
{
_id: '5f6418f13b179e3da326a1aa',
name: "John Doe",
createdAt: undefined,
updatedAt: undefined,
isActive: undefined,
}
It freaks out Mongo, it thinks that I’m trying to overwrite its internal createdAt field with undefined and throws me an error.
Interestingly, if I send a valid date in createdAt field, mongo is totally allright with that (it ignores it as it should). Only undefined
trips it 😃
Issue Analytics
- State:
- Created 3 years ago
- Reactions:2
- Comments:6 (4 by maintainers)
Top Results From Across the Web
Refine validations on object definitions don't get triggered until ...
The problem is that the .refine() function defined on the object type ... You can test it by trying the beta release via...
Read more >zod - npm
Parsing now returns a deep clone of the data you pass in. Previously it returned the exact same object you passed in. Relatedly,...
Read more >Specify a Zod schema with a non-optional but possibly ...
undefined ()]) or z.string().optional() results in the field being equivalent to IFoo2 . I'm wondering if there is a way to specify a ......
Read more >Untitled
IMPORTANT: After Zod 1.11, the value returned by `.parse` is a _deep clone_ of ... Extending objects You can add additional fields an...
Read more >Zod NPM | npm.io
npm install zod # npm yarn add zod # yarn pnpm add zod # pnpm ... const schema = z.optional(z.string()); schema.parse(undefined); // =>...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@grreeenn @sylvanaar @o-alexandrov this is fixed in zod@2.0.0-beta.9
https://github.com/vriad/zod/blob/a014ff6d041801e13021bc21fd359b3e20318ffd/src/parser.ts#L369
Probably should be