我在上诉架构中正确配置枚举时遇到问题。 我看到以下错误:
Type '{ type: StringConstructor; enum: (string | Category)[]; required: true; }' is not assignable to type 'SchemaDefinitionProperty<Category, Appeal> | undefined'.
申诉型号:
import mongoose, { Schema } from 'mongoose';
import { Appeal, Category } from './appealTypes'
const appealSchema = new mongoose.Schema<Appeal>(
{
category: {
type: Schema.Types.String,
enum: Object.values(Category),
required: true,
},
},
{ timestamps: true }
);
export default mongoose.model<Appeal>('Appeal', appealSchema)
申诉类型:
import { Types } from "mongoose";
export enum Category {
"Sadaqah",
"Zakat",
}
export interface Appeal {
_id: string;
category: Category;
}
默认情况下,除非另有说明,TypeScript 中的枚举都是数字,因此 Mongoose 无法将枚举值直接解释为字符串。
您的架构期望枚举选项是与类别值匹配的字符串数组,但您的类别枚举当前缺少显式字符串值,并且默认情况下表示为数值。
您必须明确键入枚举字符串值:
export enum Category {
Sadaqah = "Sadaqah",
Zakat = "Zakat",
}