Defining a union type in a Mongoose schema using TypeScript

Viewed 703

I define a mongoose schema in TypeScript like this.

 interface ISchema {
   prereqs: 'CONSENT' | string[]
}

 const newSchema = new Schema<ISchema>({
     prereqs: { type: Schema.Types.Mixed, required: true }
 })

I want "prereqs" to be a union type between a "constant string" and an "array of string". So I define this field in mongoose schema as "Schema.Types.Mixed" but the compiler give me this error

Type '{ type: typeof Schema.Types.Mixed; required: true; }' is not assignable to type 'SchemaDefinitionProperty<string[] | "CONSENT"> | undefined'.
Types of property 'type' are incompatible.
Type 'typeof Mixed' is not assignable to type '"string" | typeof String | StringConstructor | "String" | AnyArray<"string" | typeof String | StringConstructor | "String"> | AnyArray<...> | undefined'.
Types of construct signatures are incompatible.
Type 'new (path: string, options?: AnyObject | undefined, instance?: string | undefined) => Mixed' is not assignable to type 'new (path: string, options?: AnyObject | undefined, instance?: string | undefined) => String'.
Type 'SchemaType' is missing the following properties from type 'String': enum, lowercase, match, maxlength, and 3 more.

Well, If I define prereqs in the interface as any, it will works fine. But it will lose the type checking capability.

Is there a way to solve this?

1 Answers

There is definitely a way to keep the schema validated and add union capability for a field.

But personal thought - it slightly makes code non-readable.

You can refer this documentation here - https://mongoosejs.com/docs/discriminators.html

Related