'这'是未定义的mongoose前保存钩子
我已经为User实体创build了一个Mongoose数据库模式,并且想要在updated_at
字段中添加当前date。 我试图使用.pre('save', function() {})
callback,但每次我运行它,我得到一个错误消息,告诉我this
是未定义的。 我也决定使用ES6,我想这可能是一个原因(一切工作虽然)。 我的mongoose/节点ES6代码如下:
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.now
来解决此问题。
问题是你的箭头函数使用词法这个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() })