Skip to content

Instantly share code, notes, and snippets.

@bpceee
Last active January 27, 2022 15:42
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bpceee/c6acb6c86f5674b91eba to your computer and use it in GitHub Desktop.
Save bpceee/c6acb6c86f5674b91eba to your computer and use it in GitHub Desktop.
optimistic lock implementation in mongodb
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var ThingSchema = new mongoose.Schema({
count: Number,
version: Number,
});
var Thing = mongoose.model('Thing', ThingSchema);
var doAdd = function(id, retryTimes){
if (retryTimes == undefined) retryTimes = 1;
Thing.findById(id, function(err, thing){
thing.count++;
Thing.findOneAndUpdate({"_id": id, "version": thing.version},
{$set: {count: thing.count}, $inc: {"version": 1}},
function(err, data){
if (!data) {
console.log("retry times " + retryTimes);
if (retryTimes == 1000) {console.log("exceed retry times, failed!"); return -1;}
doAdd(id, ++retryTimes);
}
}
);
});
};
//test
var id = "53e890fbb9f46000001d8056";
doAdd(id);
doAdd(id);
doAdd(id);
@kawache
Copy link

kawache commented Oct 16, 2020

:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment