Save conflict is when 2 persons are saving the same document. For example, Person A and Person B open the same document. Person A saves the document, followed by Person B, then Person A's data over-write by Person B.
To avoid this, you can use either version check or document lock mechanism.
Version Check:
By default, when you save the document using mongoose, mongoose saves the version number in __v field. We can use the field to do version check to avoid save conflict.
Person A opens and edits the version 1 document. Meantime, Person B also opens the edit version 1 document.
Person A success save the document using below query:
posts.update({ _id: postId, __v: versionNumber } , { $set: { 'comments': updatedText }})
When Person B try to save the document using the same query, the save will be failed because of the wrong version number.
Document Lock:
Locking when Person A edit the document, saved a lock flag to the document.
When person B tries to edit the same document, the system will prompt saying the document is currently edit (lock) by Person A.
Bonus:
If you don’t want to use versioning in your schema you can disable it by passing false for the versionKey option.
schema.set('versionKey', false);
No comments:
Post a Comment