`mongoose.InferSchemaType` does not correctly infer nullable arrays
See original GitHub issuePrerequisites
- I have written a descriptive issue title
- I have searched existing issues to ensure the bug has not already been reported
Mongoose version
6.5.5
Node.js version
16.15.1
MongoDB server version
5.0.12
Description
When working with Mongoose schemas involving array fields that are nullable, mongoose.InferSchemaType
does not seem to correctly infer the schema type. The notion of optionality does not seem to be reflected.
Steps to Reproduce
Let’s suppose we create a Mongoose schema with 2 fields of 2 different types, one being an array of strings, the other an array of objects, both optional.
const TestSchema = new mongoose.Schema(
{
comments: { type: [String], default: () => undefined, required: false },
reference: {
type: [
{
type: { type: String, required: false },
value: { type: String, required: false },
},
],
default: () => undefined,
required: false,
},
},
{
collection: 'tests',
timestamps: false,
},
);
export type TestType = mongoose.InferSchemaType<typeof TestSchema>;
In TestType
, the notion of optionality of our fields seems to be lost:
The problem is the same if we replace default: () => undefined
by default: () => null
.
If we just try default: undefined
or default: null
, another problem appears:
Perhaps there is a misunderstanding/error on my side in defining the schema. If this is the case, I would be happy to receive your advices. Otherwise, it must be a bug? 🐛
Expected Behavior
{
comments?: string[];
reference?: {
type?: string;
value?: string;
}[];
}
Issue Analytics
- State:
- Created a year ago
- Comments:10 (3 by maintainers)
Top GitHub Comments
@mohammad0-0ahmad
Confirmed that this issue still happens if
strict: true
isn’t set. Following script fails to compile without--strict
. We’re looking into that to see if we can fix it.