You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose鉴别器创建文档报错:Cast to String failed for value "a"

问题分析与解决

你的代码存在几处语法和配置错误,正是这些问题导致了看似矛盾的类型转换报错,以下是具体问题和修正方案:

1. GenericSchema 语法缺失

GenericSchema中type字段的对象定义漏掉了闭合的},破坏了Schema的结构:

// 错误写法
type: { type: String, required: true, enum: ["a", "b", "c"]
// 正确写法
type: { type: String, required: true, enum: ["a", "b", "c"] }

2. ASchema 属性拼写错误

ASchema里的token字段用了错误的属性名require,正确的属性名是required:

// 错误写法
token: { type: String, require: true }
// 正确写法
token: { type: String, required: true }

3. Service.ts 语法错误

AModel.create()的对象参数未闭合括号,语法异常会干扰Mongoose的正常执行:

// 错误写法
AModel.create({
  id: "1",
  type: "a",
  token: "abc123"
};
// 正确写法
AModel.create({
  id: "1",
  type: "a",
  token: "abc123"
});

修正后的完整代码

Model.ts

import mongoose, { Document, Schema, Model } from "mongoose";

// 接口定义
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, required: true }
});

// 模型导出
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"
});

错误原因说明

这些语法错误导致Mongoose无法正确解析Schema结构,进而在文档验证时出现了混乱的错误提示——并非值的类型真的不符合要求,而是Schema本身定义不合法。修正后验证即可正常通过。

内容的提问来源于stack exchange,提问作者Bao Dang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 18:13:23