Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

How to do a document versioning in MongoDB using Driver

Requires document versioning in MongoDB while editing on the app.

I have many "Cards" created by various users. A card can be edited at any point. The app must hold all the changes in the database so that an admin can roll back to old changes.

To do that I have tried to copy and existing document which represents one card, reinsert it with a different _id which will be considered version 0. Then update the copied one with latest changes. This was I expect db to hold version 1, 2, 3 of the same document. I say same document because I am copying the first document's _id as "source_id" for later to accumulate the result.

Using MongoDB.Driver with VB.Net

Although this hasn't worked, but is it a correct way to do?

Issues: FindOneAndUpdate returns the updated document and I lose the initial data.

Saw here about how to duplicate a document, but this didn't work for me. Saw many places mentioned upsert, but the following didn't work for me either.

question from:https://stackoverflow.com/questions/65890854/how-to-do-a-document-versioning-in-mongodb-using-driver

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The solution:

While editing an existing Card, create a new with incremented version. So use InsertOne method. Find the existing card, change certain fields that required to make the card latest before insert. Use a filed that allows card to be different from the rest. Let's user "status", which can be "published"/"draft"/"reject". Now in this case, change "status" field (from "Published" to "Draft") and increment the "version" field. No need to use "FindOneAndUpdate" because this will make the initial data lost.

This way in db there will be same card details with first card's ID as a resource id with different versions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...