Last active
December 22, 2015 11:48
-
-
Save joewagner/6468168 to your computer and use it in GitHub Desktop.
Helper function to catch version errors when trying to update an Array field in a mongoose Model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// --- Dependancies --- | |
var _ = require('underscore'); | |
var mongoose = require('mongoose'); | |
// Any function that makes an update to a mongoose model that has an Array field can | |
// use this to catch version errors, and retry the update at most two times | |
var catchVersionErr = function () { | |
var updateFunc, callback, context, args = _.toArray(arguments); | |
context = args.shift(); | |
if (!(updateFunc = args.shift())) { throw new Error('catchVersionErr: must supply a function to do update'); } | |
if (!(callback = args.pop())) { throw new Error('catchVersionErr: must supply a callback'); } | |
var _count = 0; | |
// Add a wrapped callback to the args Array | |
args.push(function () { | |
var err = arguments[0]; | |
if (err instanceof mongoose.Error.VersionError && _count < 2) { | |
_count += 1; | |
return updateFunc.apply(context, args); | |
} | |
callback.apply(this, arguments); | |
}); | |
updateFunc.apply(context, args); | |
}; |
I'm finding that catchVersionErr catches the err, then retries without error - which seems fine, but my doc isn't updated. Question: when the first attempt fails, is the new __v (version) retrieved and the model updated with that new version? If not, how would this work?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example Usage extending Aaron Heckman's example: