Reputation: 1
Model.ts
import mongoose, { Document, Schema, Model } from "mongoose";
// Interfaces
export type Generic = "a" | "b" | "c";
export interface GenericDoc extends Document {
id: string;
type: Generic;
}
export interface ADoc extends GenericDoc {
type: "a";
token: string;
}
// Schema
const GenericSchema: Schema = new Schema(
{
id: { type: String, required: true },
type: { type: String, required: true, enum: ["a", "b", "c"]
},
{
discriminatorKey: "type",
collection: "test",
}
);
const ASchema: Schema = new Schema({
token: { type: String, require: true }
});
// Models
export const GenericModel = mongoose.model<GenericDoc>("Generic", GenericSchema);
export const AModel = GenericModel.discriminator<ADoc>("AModel", ASchema);
Service.ts
import { AModel } from "path/model.ts";
AModel.create({
id: "1",
type: "a",
token: "abc123"
};
Result:
Error: AModel validation failed: type: Cast to String failed for value "a" (type string) at path "type"
I don't understand why this happened since "a" has already been recognized as type string but then why would there be an error of casting it to string? Been trying to resolve this for 5 hours now. Appreciate it if someone can help. Thank you!
Upvotes: 0
Views: 57
Reputation: 1
I was just not reading the documentation carefully enough. Apparently, the first parameter for the discriminator
function should be "a" itself. Also, when I want to create an AModel, I just need to use the GenericModel and it should know how to discriminate it as an AModel from the type
property.
Upvotes: 0