If I store mongoose schema description object in the variable before creating new schema, it won't pick up proper schema options. For example:
const person = {
name: { type: String, required: true }
};
const PersonSchema = new Schema(person);
type Person = InferSchemaType<typeof PersonSchema>;
Person
type is now:
type Person = {
name?: string;
}
Incorrectly marking name
field as optional.
But when I do seemingly almost exact same thing:
const PersonSchema = new Schema({
name: { type: String, required: true }
});
type Person = InferSchemaType<typeof PersonSchema>;
Person
type is now:
type Person = {
name: string;
}
Correctly having name
marked as required.
I really have no idea why this is the case.
Anyone can explain? Thanks!
Codesandbox link: https://codesandbox.io/s/fancy-cdn-kx378p?file=/index.js
CodePudding user response:
I think I just answered myself after bit more fiddling around.
It's more of a typescript thing rather than mongoose.
It's basically happening because if I define my object like this:
const person = {
name: { type: String, required: true }
};
The object is still mutable so typescript won't assume person.name
is of any value and therefore name
becomes string | undefined
essentially making this prop optional.
The solution is to tell typescript compiler, that this object won't change by adding as const
.
This will work fine:
const person = {
name: { type: String, required: true }
} as const;
const PersonSchema = new Schema(person);
type Person = InferSchemaType<typeof PersonSchema>;
Results in:
type Person = {
name: string;
}