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?