Node.js Mongoose, how to catch error in post save Node.js Mongoose, how to catch error in post save mongoose mongoose

Node.js Mongoose, how to catch error in post save


I'm answering with what I found out right now by stumbling on a similar issue.

I'll be focusing in the "catch error in post save" part as I'm not sure, by now if modifying and re-saving the document in this way might or might not cause some trouble. So I'm not sure this will work fine for your specific needs, but you can give it a try.

My scenario is similar to yours, but slightly different:

  1. I want to associate an unique, random, short code to each document of my collection.
  2. I do not generate it randomly at each insertion, but I pre-generated a collection of 1M random codes stored in documents like this:

    {  value: "khsda",  status: "FREE"}
  3. Each time I want to insert a new document with an associated code I do the fallowing:

    1. In .pre('validate',...) I select a "FREE" code and set its status to "PENDING".
    2. I assign the new document code to the value of the picked code.
    3. Now, if the saving process goes fine I want to change the status to "TAKEN" otherwise, I want to freed the code, setting its status back to "FREE".
    4. To know If everything went fine, I hook a .post('save',...) middleware that changes the code status to "TAKEN"
    5. To know If something went wrong, I hook a .post('validation',...) middleware. But here's the quirk: the signature of the function I pass to the middleware must be function(error, doc, next). This middleware will be called only if an error occurs in the validation process and lets me put back the status of the code to "FREE".

So, basically, you could hook a middleware like this:

schema.post('save', function(err, doc, next) {    // Handle the error...});

I'm not sure if attempting to change and re-save the document at this point will cause any issue, but by logic, the save operation should already have been aborted and here you can control the bubbling of the error through the next(). If you attempt a new save and then call next() without any error as argument, It might work as you need.

Let me know if this works.