作者:铁打的岳小野 | 来源:互联网 | 2023-05-19 05:22
This question already has an answer here:
这个问题在这里已有答案:
- Mongoose pre/post midleware can't access [this] instance using ES6 1 answer
- Mongoose pre / post midleware无法使用ES6 1答案访问[this]实例
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:
我为User实体创建了一个Mongoose数据库模式,并希望在updated_at字段中添加当前日期。我正在尝试使用.pre('save',function(){})回调,但每次运行它时都会收到一条错误消息,告诉我这是未定义的。我也决定使用ES6,我想这可能是一个原因(尽管一切正常)。我的Mongoose / Node 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
The error message is:
错误消息是:
undefined.updated_at = currentDate.now;
^
TypeError: Cannot set property 'updated_at' of undefined
EDIT: 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
.
编辑:通过使用@ vbranden的答案并将其从词法函数更改为标准函数来解决此问题。但是,我遇到了一个问题,虽然它不再显示错误,但它没有更新对象中的updated_at字段。我通过将this.updated_at = currentDate.now更改为this.updated_at = currentDate来修复此问题。
1 个解决方案