piggyback
piggyback

Reputation: 9264

Update last_edit with a middleware in Mongoose and Nodejs

Let's consider this schema:

var elementSchema = new Schema({
  name: String,
  last_edit: { type: Date, default: Date.now }
});

Now, every time I update any element.name I would like that mongoose updates directly the last_edit time.

In Mongoose Middleware docs it says:

var schema = new Schema(..);
schema.pre('save', function (next) {
  // do stuff
  next();
});

I might update it instead of // do stuff, however the document to be saved is not passed, any hint?

Upvotes: 0

Views: 247

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312035

In 'save' middleware, this is a reference to the document being saved:

schema.pre('save', function (next) {
  this.last_edit = Date.now();
  next();
});

Upvotes: 3

Related Questions