我为用户实体制作了Mongoose数据库架构,并希望在updated_at
字段中添加当前日期。我正在尝试使用.pre('save', function() {})
回调,但是每次运行回调时,都会收到一条错误消息,告诉我this
未定义。我还决定使用ES6,我想这可能是这样做的原因(尽管一切正常)。我的猫鼬/节点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
。
问题是您的箭头函数使用了词汇表https://developer.mozilla.org/zh-CN/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()
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句