Last active
January 27, 2022 15:42
-
-
Save bpceee/c6acb6c86f5674b91eba to your computer and use it in GitHub Desktop.
optimistic lock implementation in mongodb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
:)