From ce7fb11815fcadc8412bfdcaa2cd31c8647bcdad Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Thu, 26 Apr 2018 17:56:20 -0400 Subject: [PATCH] feat(error): add version number to VersionError backport to 4.x of dd2483d1167f0878ca075835858d5708dfc307ac --- lib/error/version.js | 5 +++-- lib/model.js | 7 ++++--- test/versioning.test.js | 1 + 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/lib/error/version.js b/lib/error/version.js index 719c07f1254..33d1bd88e66 100644 --- a/lib/error/version.js +++ b/lib/error/version.js @@ -13,10 +13,11 @@ var MongooseError = require('./'); * @api private */ -function VersionError(doc) { +function VersionError(doc, currentVersion) { MongooseError.call(this, 'No matching document found for id "' + doc._id + - '"'); + '" version ' + currentVersion); this.name = 'VersionError'; + this.version = currentVersion; } /*! diff --git a/lib/model.js b/lib/model.js index 1d1defedd7b..8b85100599f 100644 --- a/lib/model.js +++ b/lib/model.js @@ -258,16 +258,17 @@ Model.prototype.$__save = function(options, callback) { var doIncrement = VERSION_INC === (VERSION_INC & _this.$__.version); _this.$__.version = undefined; + var key = _this.schema.options.versionKey; + var version = _this.getValue(key) || 0; + if (numAffected <= 0) { // the update failed. pass an error back - var err = new VersionError(_this); + var err = new VersionError(_this, version); return callback(err); } // increment version if was successful if (doIncrement) { - var key = _this.schema.options.versionKey; - var version = _this.getValue(key) | 0; _this.setValue(key, version + 1); } } diff --git a/test/versioning.test.js b/test/versioning.test.js index db2e9854dc3..4e6856c8b08 100644 --- a/test/versioning.test.js +++ b/test/versioning.test.js @@ -265,6 +265,7 @@ describe('versioning', function() { function test4(err, a, b) { assert.ok(/No matching document/.test(err), err); assert.equal(a._doc.__v, 5); + assert.equal(err.version, b._doc.__v - 1); a.set('arr.0.0', 'updated'); var d = a.$__delta(); assert.equal(a._doc.__v, d[0].__v, 'version should be added to where clause');