我为一个用户实体创建了一个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.

推荐答案

问题是你的arrow函数使用了这个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()
})

Mongodb相关问答推荐

在MongoDB中是否可以按递增顺序更新多个文档?

数组字段包含其他字段的数组值

如何匹配 MongoDB 中同一文档中两个字段的比较?

MongoDB 使用 pymongo 收集 500K 文档的写入速度很差

可变用户 Select

从 kubectl exec 获取返回值到 powershell 脚本

MongoDB聚合 - 用另一个数组过滤数组

在 mongodb 聚合中的阶段之后输出具有序列数字 id 的新集合

Mongo查询子文档的多个字段

Mongoexport 在日期范围内使用 $gt 和 $lt 约束

如何使用 C# MongoDB 驱动程序检索字段子集?

如何使用sailsjs v0.10连接mongodb?

Golang/mgo:如何让 MongoDB 在字段中使用当前时间?

无法从 javascript 打印 BSON 对象

在 mongodb 中插入当前日期时间

mongodb:upserting:仅在插入文档时设置值

MongoDB $elemMatch $in

如何在 $match 内的 mongodb 聚合查询中使用 $regex

Mongodb 按字段名称查找任何值

从 Grunt 任务中启动 MongoDB