Showing posts with label Mongoose. Show all posts
Showing posts with label Mongoose. Show all posts

Saturday, July 24, 2021

New in Mongoose 5.10: Optimistic Concurrency - Safe Save Conflict

Optimistic concurrency is a better way to handle save conflict compare to the article I wrote previously.

https://scalaoncloud.blogspot.com/2021/03/how-to-avoid-save-conflict-in-mongoose.html


Optimistic concurrency tracks the version of the document and increments the version every time save(). If the version of the document in the database changed between when you loaded the document and when you save(), Mongoose will throw an error.

https://mongoosejs.com/docs/guide.html#optimisticConcurrency

https://thecodebarbarian.com/whats-new-in-mongoose-5-10-optimistic-concurrency.html 

Thursday, March 25, 2021

How to avoid save conflict in mongoose?

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);

Wednesday, March 24, 2021

What if the ref document deleted from the backend in Mongoose's Populate Ref?

Mongoose's populate joins 2 collections by using the ref. 

What if the ref document deleted from the backend?

You still can see the ref when you searching using MongoDb driver and MongoDb Compass. However, you won't see the ref when you search using mongoose.