我試圖在基于另一個的模式中有一個欄位。
我找到了這個解決方案:
const PostSchema = new Schema({
title: { type: String, required: true },
titleUpperCase: { type: String }
content: { type: String, required: true },
creation: { type: Date, default: Date.now() }
})
PostSchema.pre('save', (next) => {
this.titleUpperCase = this.title.toUpperCase()
next()
})
在上面的代碼中,我希望 titleUpperCase 欄位的值基于標題欄位,但問題是我給出了一個錯誤說: TypeError: Cannot read properties of undefined (reading 'title')
uj5u.com熱心網友回復:
因為您使用的是箭頭函式,所以“this”關鍵字不是您想要的。基本上,每當您在這種情況下使用 mongoose 鉤子(如預保存鉤子)時,您應該始終使用普通函式進行回呼。
PostSchema.pre('save', function(next) {
this.titleUpperCase = this.title.toUpperCase()
next()
})
我相信這應該有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/359509.html
標籤:javascript 节点.js 表达 猫鼬
