node.jsmongodbmongoosemongoose-plugins

Use mongoose hook to retry saving on duplicate key error


I would like to use a mongoose middleware hook to re-try saving a document in case the initial save failed with a duplicate key error. The use case is as follows:

My model uses slugs for identification which are automatically generated. E.g. item, item-2, item-3, …, item-n. In case, item already exists, a counter should be added to the slug. I cannot check the "next" slug in advance, as I need to avoid conflicts under any circumstance.

As this logic will be involved in several different models, I would like to isolate it into a mongoose plugin.

Is the idea at all possible? E.g. schema.post('save', handler) only get executed on a successful save. Are there any other hooks, which I can exploit?


Solution

  • I finally went with the solution used by mongoose-uniqueslugs, which I adapted to our needs. While this variant does not solely work with pre/post hooks, it ensures atomicity (i.e. not checking for available slugs in advance and then saving, but simply re-trying).

    The central idea is to override the model's save function (see enhanceModel function) and provide a wrapper which catches unique errors by slug collisions and then re-trying to save (instead of the random string appended, we want for a sequential number approach).