I created a Mongoose database schema for the User object and want to add the current date in the updated_at field. I am trying to use the .pre('save', function() {}) callback, but every time I run it, an error message appears indicating that this is undefined. I also decided to use ES6, which, I think, could be the reason for this (everything works). My Mongoose / Node ES6 code is below:
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
Error message:
undefined.updated_at = currentDate.now; ^ TypeError: Cannot set property 'updated_at' of undefined
EDIT: This is fixed using @ vbranden's answer and changing it from a lexical function to a standard function. However, I had a problem when, although it no longer showed an error, it did not update the updated_at field in the object. I fixed this by changing this.updated_at = currentDate.now to this.updated_at = currentDate .
Tom oakley
source share