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

在Mongoose中定义ObjectId类型属性时出现TypeScript错误

解决Mongoose 6.x + TypeScript Schema定义中的ObjectId类型错误

你遇到的错误是因为Schema定义里的type字段使用了错误的ObjectId类型标识。以下是具体的解决方法和原因:

问题根源

在Mongoose的Schema定义中,type字段需要传入Schema层面的类型构造函数(来自Schema.Types),而你使用的Types.ObjectId是用于表示MongoDB文档中ObjectId实例的类型,并非Schema定义时所需的类型标识,因此TypeScript会抛出类型不兼容的错误。

修正方案

方案1:使用Schema.Types.ObjectId

将Schema中的type: Types.ObjectId替换为type: Schema.Types.ObjectId,这是Mongoose官方推荐的Schema类型定义方式:

import { Schema, Types } from 'mongoose';

interface Foo {
  _id: Types.ObjectId;
  bar: Types.ObjectId;
}

const FooSchema = new Schema<Foo>({
  _id: { type: Schema.Types.ObjectId },
  bar: { type: Schema.Types.ObjectId },
});

方案2:使用字符串类型标识

Mongoose支持直接用字符串'ObjectId'来指定类型,这种方式更简洁,且TypeScript能正确推导类型:

import { Schema, Types } from 'mongoose';

interface Foo {
  _id: Types.ObjectId;
  bar: Types.ObjectId;
}

const FooSchema = new Schema<Foo>({
  _id: { type: 'ObjectId' },
  bar: { type: 'ObjectId' },
});

额外提示

如果不需要对_id字段做自定义配置(比如禁用、设置默认值等),可以不用显式定义该字段,Mongoose会自动为每个Schema添加默认的_id字段,类型为ObjectId。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:57:30