Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.91k stars 3.83k forks source link

Union schema types: paths that can be one of multiple types #10894

Open israelKusayev opened 3 years ago

israelKusayev commented 3 years ago

Do you want to request a feature or report a bug?

What is the current behavior?

I have a birthday field that the client send a string like "03/02/2000" and I convert it via set to a Date Is it possible to define two types the first one String (the first validation by mongoose to check if it's a string) and a second type of Date (when I read it from the DB)

birthday: {
    type: SchemaTypes.Date
    set: (value: string) => {
        return value ? startOfDay(parse(value, 'DD/MM/YYYY', new Date())).toISOString() : null;
    }
}

What is the expected behavior?

Right now I get the following error mongoose validation error Cast to Date failed for value "03/02/2000" (type string) at path "birthday"

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.

Currently I use the "latest version" 6.0.11

IslandRhythms commented 3 years ago

You either want to use a discriminator or Define it as a mixed type

israelKusayev commented 3 years ago

I don't think discriminator is a good solution here

(and SchemaTypes.Mixed is just like any in typescript, but it's better)

I personally would expect something like typescript's union type :)

type: SchemaTypes.Date | SchemaTypes.String

vkarpov15 commented 3 years ago

We don't currently support union types, but as you mentioned, setters can help. Just write a setter that makes sure properly formatted strings are converted to dates.