Amio.io
Amio.io

Reputation: 21565

MongoDB: verifying document was not updated

We would like to apply some auditing in our current project. For that we created a scenario but I don't see how to make point 1 and 2 atomic.

Scenario

Every document has to have a timestamp that will server as a version. When saving a document we will:

  1. Verify document was not changed - first compare the timestamps of the latest document docLatest with the document we would like to store docUpdated. The timestamps must be equal.
    • If not, save request is refused.
    • If ok, go to next point.
  2. Update the document
  3. Create diff with the previous doc - The latest document must be our last document. We will create a diff and store it.

Upvotes: 0

Views: 41

Answers (1)

vdj4y
vdj4y

Reputation: 2669

I stumble upon this idea once. My idea will utilize long_polling technique. I am not going to tell you how to architect your data, but you can convert date to numeric value, and compare by it.

for 1 and 2, you can convert Date-format to number, the schema will look something like below:

var document= { 
   updatedAt: { type: Number, default: Date.parse(new Date()) } 
 }

then for every document submitted by client, just check, if the

if(latestDocument.updatedAt - prevDocument.updatedAt > 0) {
   //if latest's timestamp is bigger than prev, then store it in mongodb

} else {
  //if latest document is the same or even older, just ignore this document
}

for number 3. I found that, if the document has changed, do you even need to diff it? I decide to follow react/flux's method, if the document has changed just replaced the whole document.

Upvotes: 1

Related Questions