Mongoose错误信息‘xxx may not be used as a schema pathname‘原因及其解决方式

在使用MongoDB和Mongoose的后端服务中,尝试添加一个字段到schema时遇到'Mongoose错误信息:xxx may not be used as a schema pathname'。错误源于使用了Mongoose保留的关键词作为字段名。解决方案是避免在schema设计时使用这些保留关键词。Mongoose 5.x和4.x的保留关键词列表不同,详细信息可参考Mongoose官方文档和StackOverflow讨论。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

公司的后端服务采用了MongoDB + Mongoose的设计,今天的一个需求中需要标记某些文档是否被人工修改,于是便在其schema中加入了一个名为isModified字段。

const schema = {
  // ...
  isModified: {
    type: Boolean,
    required: false,
    default: false,
  },
  // ...
}

在添加后运行程序出现了下述错误信息:

Error: `isModified` may not be used as a schema pathname
    at Schema.path (.../node_modules/mongoose/lib/schema.js:644:11)
    at Schema.add (.../node_modules/mongoose/lib/schema.js:519:14)
    at new Schema (.../node_modules/mongoose/lib/schema.js:130:10)
    ...

这个错误比较少见,国内网站上也基本上没有对于该问题的具体解答,只是说到将错误的字段名改为其它名称。

造成该错误的原因为schema定义的属性中包含了Mongoose保留的关键词。从Mongoose的源码中可以很清楚的看到该错误的原因:

// some path names conflict with document methods
const firstPieceOfPath = path.split('.')[0];
if (reserved[firstPieceOfPath]) {
  throw new Error('`' + firstPieceOfPath + '` may not be used as a schema pathname');
}

因此,只要在schema设计时避免使用Mongoose保留的关键词即可,具体的Mongoose保留关键词如下节所示。

关键词列表

Mongoose 5.x中保留的关键词如下(以字母顺序排列):

  • _posts
  • _pres
  • collection
  • emit
  • errors
  • get
  • init
  • isModified
  • isNew
  • listeners
  • modelName
  • on
  • once
  • populated
  • prototype
  • remove
  • removeListener
  • save
  • schema
  • toObject
  • validate

若使用的是Mongoose 4.x及之前的版本,其schema保留的关键词与5.x有一些差异,具体的保留关键词如下:

  • _events
  • _posts
  • _pres
  • collections
  • db
  • emit
  • errors
  • get
  • init
  • isNew
  • modelName
  • on
  • options
  • set
  • schema
  • toObject

参考资料

欢迎大家关注我的公众号“风纸”,或是扫下面的二维码关注👇
风纸

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值