Mongoose如何基于另一字段设置字段值?pre save钩子报错如何解决?
Mongoose 依赖字段动态生成报错解决方案
错误根因
报错TypeError: Cannot read properties of undefined (reading 'title')的核心原因是pre('save')钩子使用了箭头函数作为回调:
箭头函数不会绑定独立的this上下文,会继承外层作用域的this,此处外层作用域没有对应的Mongoose文档实例,因此this为undefined,读取this.title就会抛出错误。
修复方案
将箭头函数替换为普通函数声明,即可正确绑定文档实例的this上下文:
const PostSchema = new Schema({ title: { type: String, required: true }, titleUpperCase: { type: String }, content: { type: String, required: true }, // 额外优化:Date.now去掉括号,避免Schema初始化时就固定时间 creation: { type: Date, default: Date.now } }) PostSchema.pre('save', function(next) { this.titleUpperCase = this.title.toUpperCase() next() })
额外说明
- 若使用Mongoose 6及以上版本,支持异步钩子写法,无需手动调用
next方法:
PostSchema.pre('save', async function() { this.titleUpperCase = this.title.toUpperCase() })
- 原代码中
creation字段的默认值写为Date.now()会导致所有文档的默认创建时间固定为Schema定义的时间,改为Date.now(不带括号)才会在每个文档新建时动态生成当前时间。
内容的提问来源于stack exchange,提问作者user16735766
相关产品推荐
相关产品推荐

