猫鼬预保存钩子中未定义"this" [英] 'this' is undefined in a Mongoose pre save hook
问题描述
我为User实体制作了Mongoose数据库架构,并想在updated_at
字段中添加当前日期.我正在尝试使用.pre('save', function() {})
回调,但是每次运行它时,都会收到一条错误消息,告诉我this
是未定义的.我还决定使用ES6,我想这可能是这样做的原因(尽管一切正常).我的Mongoose/Node ES6代码如下:
I have made a Mongoose database schema for a User entity, and want to add the current date in an updated_at
field. I am trying to use the .pre('save', function() {})
callback but every time I run it I get an error message telling me this
is undefined. I've also decided to use ES6, which I guess could be a reason for this (everything works though). My Mongoose/Node ES6 code is below:
import mongoose from 'mongoose'
mongoose.connect("mongodb://localhost:27017/database", (err, res) => {
if (err) {
console.log("ERROR: " + err)
} else {
console.log("Connected to Mongo successfuly")
}
})
const userSchema = new mongoose.Schema({
"email": { type: String, required: true, unique: true, trim: true },
"username": { type: String, required: true, unique: true },
"name": {
"first": String,
"last": String
},
"password": { type: String, required: true },
"created_at": { type: Date, default: Date.now },
"updated_at": Date
})
userSchema.pre("save", (next) => {
const currentDate = new Date
this.updated_at = currentDate.now
next()
})
const user = mongoose.model("users", userSchema)
export default user
错误消息是:
undefined.updated_at = currentDate.now;
^
TypeError: Cannot set property 'updated_at' of undefined
通过使用@vbranden的答案并将其从词法函数更改为标准函数来解决此问题.但是,我遇到了一个问题,尽管它不再显示错误,但没有更新对象中的updated_at
字段.我通过将this.updated_at = currentDate.now
更改为this.updated_at = currentDate
来解决此问题.
Fixed this by using @vbranden's answer and changing it from a lexical function to a standard function. However, I then had an issue where, while it wasn't showing the error anymore, it wasn't updating the updated_at
field in the object. I fixed this by changing this.updated_at = currentDate.now
to this.updated_at = currentDate
.
推荐答案
the issue is your arrow function uses lexical this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
更改
userSchema.pre("save", (next) => {
const currentDate = new Date
this.updated_at = currentDate.now
next()
})
到
userSchema.pre("save", function (next) {
const currentDate = new Date()
this.updated_at = currentDate.now
next()
})
这篇关于猫鼬预保存钩子中未定义"this"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!