Mongoose versioning: when is it safe to disable it?

拥有回忆 提交于 2020-11-30 11:17:12

问题


From the docs:

The versionKey is a property set on each document when first created by Mongoose. This keys value contains the internal revision of the document. The name of this document property is configurable. The default is __v. If this conflicts with your application you can configure as such:

[...]

Document versioning can also be disabled by setting the versionKey to false. DO NOT disable versioning unless you know what you are doing.

But I'm curious, in which cases it should be safe to disable this feature?


回答1:


The version key purpose is optimistic locking.

When enabled, the version value is atomically incremented whenever a document is updated.

This allow your application code to test if changes have been made between a fetch (bringing in version key 42 for example) and a consequent update (ensuring version value still is 42). If version key has a different value (eg. 43 because an update has been made to the document), your application code can handle the concurrent modification.

The very same concept is often used in relational databases instead of pessimistic locking that can bring horrible performance. All decent ORMs provide such a feature. For example it's nicely described in ObjectDB documentation. It's an object database implemented in Java but the same concept applies.

The blog post linked in Behlül's comment demonstrate the optimistic locking usefulness with a concrete example, but only for arrays changes, see below.

On the opposite, here is a simple case where its useless: a user profile that can be edited by its owner ownly. Here you can get rid of optimistic locking and assume that the last edit always wins.

So, only you know if your application need optimistic locking or not. Use case by use case.

The Mongoose situation is somewhat special.

Optimistic locking is enabled only for arrays because the internal storage format uses positional index. This is the issue described by the blog post linked in the question's comment. I found the explanation given in the mongoose-orm mailing list pretty clear: if you need optimistic locking for other fields, you need to handle it yourself.

Here is a gist showing how to implement a retry strategy for an add operation. Again, how you want to handle it depends on your use cases but it should be enough to get you started.

I hope this clears things up.

Cheers



来源:https://stackoverflow.com/questions/17810637/mongoose-versioning-when-is-it-safe-to-disable-it

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