mongoose-sequence icon indicating copy to clipboard operation
mongoose-sequence copied to clipboard

Increate the count only when creation success.

Open cwang1221 opened this issue 3 years ago • 1 comments

Dear Experts,

I found the count is increased no matter if the creation of the document success or not. E.g.

  1. I create a new user, the count will be 1
  2. I try to create the second user, but since I give a duplicate key to it, the creation failed (err.name === "MongoError" && err.code === 11000)
  3. I create a new user, the count is 3, but actually it should be 2.

Any idea on this? Thank you so much!

cwang1221 avatar Feb 07 '21 04:02 cwang1221

Yes the hook used is a pre-save hook, so the counter is incremented before the document is actually saved. This is safer than a post hook and better mimic the SQL behavior. At the moment there's no option to use a post hook but you can use a workaround. You can disable hooks completely and run manual increment by yourself. See the disable_hooks options and the manual increment documentation

ramiel avatar Feb 07 '21 18:02 ramiel