【问题标题】:'this' is undefined in a Mongoose pre save hook [duplicate]'this' 在 Mongoose 预保存挂钩中未定义 [重复]
【发布时间】:2016-09-18 19:15:02
【问题描述】:

我为一个用户实体创建了一个 Mongoose 数据库模式,并希望在 updated_at 字段中添加当前日期。我正在尝试使用.pre('save', function() {}) 回调,但每次运行它时都会收到一条错误消息,告诉我this 未定义。我还决定使用 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

错误信息是:

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 来解决此问题。

【问题讨论】:

标签: node.js mongodb mongoose ecmascript-6


【解决方案1】:

问题是你的箭头函数使用词法 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()
})

【讨论】:

  • 谢谢!这不再给出错误,但实际上并没有将 updated_at 字段添加到我在创建新用户时通过路由器输出的 JSON 对象(在路由文件中)。如果我这样做console.log(this.updated_at),它只会输出undefined。你知道为什么会这样吗?
  • 尝试使用 new Date() 而不是 new Date
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-29
  • 1970-01-01
  • 2020-05-13
  • 1970-01-01
  • 2019-10-01
  • 2019-04-10
相关资源
最近更新 更多