Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose hook "pre/post save" not working for findOneAndUpdate

I'm using nodejs + express + mongoose.

I add "pre/post save" hook for a module, it works fine with save function. But when I use findOneAndUpdate (create if it not exist), the hook is not called.

It seemed the only way I can do is separate findOneAndUpdate to two function, search item first then do create.

Is there a better idea to solve this problem?

like image 542
Fancyoung Avatar asked Dec 20 '22 22:12

Fancyoung


1 Answers

From mongoose documentation:

Although values are cast to their appropriate types when using the findAndModify helpers, the following are not applied:

  • defaults
  • setters
  • validators
  • middleware

If you need those features, use the traditional approach of first retrieving the document.

reference

UPDATE: Since Mongoose 4.0 you could use runValidators option, from Changelog:

#860: You can optionally run validators and set defaults if a new document is created on update() and findOneAndUpdate() calls. In order to access these features, you must explicitly set the runValidators and setDefaultsOnInsert options when you call update() or findOneAndUpdate(). Note that the setDefaultsOnInsert option is not compatible with MongoDB <= 2.2. Further note update() and findOneAndUpdate() explicitly run validators with a null context (that is, this === null in the validator function).

like image 72
krasu Avatar answered Apr 12 '23 23:04

krasu