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

Mongoose报错:`Bt`不是`category`路径有效类型,未改代码却触发

解决Mongoose Schema中Bt无效类型错误

问题描述

暂停项目开发后回归,遇到未见过的错误:

TypeError: Invalid schema configuration: `Bt` is not a valid type at path `category`. See [site] for a list of valid schema types.

对应的代码片段:

const ProductSchema = new Schema(
  {
    title: { type: String, required: true },
    description: String,
    price: { type: Number, required: true },
    images: [{ type: String }],
    category: {
      type: mongoose.Types.ObjectId,
      ref: "Category",
      required: false,
    },
    properties: { type: Object },
  },
  {
    timestamps: true,
  }
);

export const Product = models.Product || model("Product", ProductSchema);

可能的原因及解决方法

  • Mongoose类型引用方式问题
    部分Mongoose版本中,直接使用mongoose.Types.ObjectId可能出现类型解析异常,建议改用Schema实例的Types属性:

    category: {
      type: Schema.Types.ObjectId, // 替换原mongoose.Types.ObjectId
      ref: "Category",
      required: false,
    },
    
  • 模型缓存残留
    如果你使用Next.js这类SSR框架,models.Product的缓存可能保留了旧的错误Schema定义。尝试删除框架缓存目录(比如Next.js的.next文件夹),重启开发服务器。

  • 依赖版本变更
    暂停开发期间Mongoose可能自动升级,导致API兼容问题。查看package.json中的mongoose版本,回退到之前的稳定版本(比如运行npm install mongoose@x.x.x指定版本),或者查阅Mongoose更新日志确认类型相关的变更。

  • 关联模型异常
    检查Category模型的定义是否正确,确保模型已正确导出且名称与ref: "Category"完全一致,避免关联模型不存在引发的间接错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 14:42:51