Mongoose Schema使用ObjectId类型时提示ReferenceError未定义报错
报错原因
抛出ReferenceError: ObjectId is not defined是因为:
ObjectId既不是Node.js的全局内置对象,也没有在当前代码文件中被声明或导入,运行时无法识别该标识符,因此触发未定义错误。- Mongoose的ObjectId属于内置的Schema专属类型,没有挂载到全局作用域,不能直接裸写调用。
修复方案
你可以选择以下任意一种方式修复:
方案1:直接引用Mongoose内置Schema类型
将字段的type属性值改为mongoose.Schema.Types.ObjectId即可,无需额外声明。如果roleId、menuPageId是关联其他集合的外键,可以搭配ref属性指定关联的模型名,后续可通过populate()实现关联查询。
修复后完整代码:
const mongoose = require("mongoose"); const permissionsSchema = new mongoose.Schema({ roleId: { type: mongoose.Schema.Types.ObjectId, ref: "Role", // 非必填,关联对应角色模型,无关联需求可删除 required: true, }, menuPageId: { type: mongoose.Schema.Types.ObjectId, ref: "MenuPage", // 非必填,关联对应菜单页模型,无关联需求可删除 required: true, }, readAccess: { type: Boolean, required: true, }, createAccess: { type: Boolean, required: true, }, editAccess: { type: Boolean, required: false, }, deleteAccess: { type: Boolean, required: false, }, }); const Permissions = mongoose.model("Permissions", permissionsSchema); module.exports = Permissions;
方案2:提前解构声明ObjectId
如果觉得长路径写法繁琐,可以在文件头部提前将ObjectId从Mongoose中解构出来,后续即可直接在Schema中使用:
const mongoose = require("mongoose"); // 提前声明引入Schema类型下的ObjectId const ObjectId = mongoose.Schema.Types.ObjectId; const permissionsSchema = new mongoose.Schema({ roleId: { type: ObjectId, required: true, }, menuPageId: { type: ObjectId, required: true, }, // 其余字段配置和原代码一致 readAccess: { type: Boolean, required: true, }, createAccess: { type: Boolean, required: true, }, editAccess: { type: Boolean, required: false, }, deleteAccess: { type: Boolean, required: false, }, }); const Permissions = mongoose.model("Permissions", permissionsSchema); module.exports = Permissions;
注意:不要误用
mongoose.Types.ObjectId定义Schema字段类型,该API用于生成、转换ObjectId值,并非Schema字段类型定义方法,混用会导致字段类型校验异常。
内容的提问来源于stack exchange,提问作者Badr-Eddine El mostaine
相关产品推荐
相关产品推荐

