Boris Zagoruiko
Boris Zagoruiko

Reputation: 13174

Depends on query change document in mongoose pre('update')

I want to change lastActiveAt field everytime when model is updated with {active: true}. I have something like this:

MySchema.pre('update', function(next) {
  if (this._compiledUpdate.$set.active) {
    this.update({}, {lastActiveAt: new Date()});
  }
  next();
});

// ...

MyModel.update({/* ... */}, {active: true});

It works but I don't like that underscore in _compiledUpdate. Is there a recommended way to access query in pre('update') middleware?

Upvotes: 0

Views: 182

Answers (1)

hassansin
hassansin

Reputation: 17508

You can try this.getUpdate() method to get the update query:

MySchema.pre('update', function(next) {
  if (this.getUpdate().$set.active) {
    this.update({}, {lastActiveAt: new Date()});
  }
  next();
});

Ref: https://github.com/Automattic/mongoose/issues/2812

Upvotes: 1

Related Questions