I have a Node.js server which has to handle 6 concurrent requests. Each request reads a document from MonogDB database and then modifies it.
So, when we send 6 requests concurrently they all read the same data item and modify it but I want that value modified by the first request should be read by the second request and then it should be able to modify it further and so on.
For example, I have a data item called, x with initial value 'a'. The first request modifies it to 'ab'. So, the second request now should read 'ab' and not 'a'. But it always reads 'a' because they are coming concurrently.
I have tried to apply semaphore, mutex, async.series, async.waterfall, sleep and promises but nothing worked. Probably I am not using them correctly. So, how should they be used to handle these concurrent requests in a synchronous manner.
Or is there any other way of doing it? Can we do something with timestamp ordering protocol? If yes, then how can I apply it in Node.js?
This is the code that I want to run for these concurrent requests-
app.get('/urltest', function (req, res) {
var q=require('url').parse(req.url,true).query;
var s=q.s;
MongoClient.connect(url, function(err, db) {
if(err)
throw err;
db.collection( 'Comp' ).find({no:2}).snapshot().forEach(
function (elem) {
db.collection( 'Comp' ).findAndModify (
{ no : elem.no },
[['no', 1]],
{ $set : { age:elem.age+s } }, {new:true},
function( err, result ) {
if ( err ) console.log( err);
console.log("after update: "+result.value.age);
res.end("success");
}
);
});
});
});
Here I am sending requests like - http://192.168.197.140:8081/urltest?s=b, http://192.168.197.140:8081/urltest?s=c, http://192.168.197.140:8081/urltest?s=d, etc. concurrently.
Now, they can run in any order. But I want all 'b', 'c', 'd' etc to be appended. And thus the output for each should look somewhat like - 'ab', 'abc', 'abcd' and so on.
But the output I get is- 'ab', 'ac', 'ad'.
How exactly should I use promise to make sure these requests execute in a synchronous manner?