Mongoose VersionError: No matching document found for id when document is being saved

非 Y 不嫁゛ 提交于 2021-02-18 13:01:18

问题


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.


回答1:


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:

  1. v1 is sent to client
  2. v1 is saved, and updated to v2 in Mongo DB
  3. v1 is trying to be saved again, but Mongo DB already has v2 stored, error is thrown

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.



来源:https://stackoverflow.com/questions/54792749/mongoose-versionerror-no-matching-document-found-for-id-when-document-is-being

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!