I am repeatedly seeing the following error when synchronizing a users cart through a "/sync/" API request. This is called whenever a user changes the contents of their shopping cart.
VersionError: No matching document found for id "2y4b1hq601cd013e0af25e32" version 4 modifiedPaths "cart, cart.items, cart.updatedAt" at VersionError.MongooseError [as constructor] (/node_modules/mongoose/lib/error/mongooseError.js:13:11) at new VersionError (/node_modules/mongoose/lib/error/version.js:18:17) at generateVersionError (/node_modules/mongoose/lib/model.js:398:10) at model.Model.save (/node_modules/mongoose/lib/model.js:460:27) at /controllers/shoppingCart/index.js:48:14 at /node_modules/mongoose/lib/model.js:4670:16 at /node_modules/mongoose/lib/utils.js:258:16 at _hooks.execPost (/node_modules/mongoose/lib/query.js:4065:11) at /node_modules/kareem/index.js:135:16 at process._tickCallback (internal/process/next_tick.js:61:11)
The exact code line is the following:
req.session.save();
delete user.__v;
>> user.save();
return res.send();
I've tried user.increment() but this doesn't seem to fix this, nor deleting user.__v I am assuming this is conflicting versions, and I want versioning on my user objects, I just need to force the cart to always sync to the latest version.
While it would appear a .save() is the right approach here, an .update() command would get the job done while ignoring "race conditions" that cause this error to occur. Mongo DB is throwing this error because it is concerned that I am saving an older version of the document that has already been updated:
A better approach is to send v1 to the client and when the cart object changes, synchronize the object with the new cart object no matter what. This can be done via .update() rather than through .save().
This is because .save() watches and cares about version controls, while .update() will update the object regardless of version control.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With