Assume that the basic data is:
{"Name": "cb", "data": 0 ,}
Sometimes, to make full use of multiple cores, multiple node processes are enabled at the same time. However, if some code involves operations on mongodb, the following occurs.
Ideally, the data obtained after multiple processes are executed is:
{& Quot; name & quot;: & quot; cb & quot;, & quot; data & quot;: 6000, & quot ,}
Not actually!
Let's see what the results are.
Co (function *(){
For (var I = 0; I <3000; I ++ ){
Var getTest = yield fetch CTest. findOne ({
"Name": "cb"
},
{
"Fields ":{
"_ Id": 0
}
});
GetTest. data = getTest. data + 1;
Console. log (getTest );
Yield fetch CTest. update ({
"Name": "good"
},
{
"$ Set": getTest
});
}
})();
The above program has two operations at the same time, and multiple processes operate on one data at the same time.
The possible result is:
Multi-process Mongo
We know that Mongo does not support transactions. If you can tolerate the weak consistency above, it is okay. But if you cannot tolerate it, either consider MySql relational database or solve the transaction problem by yourself.
Next I will explain how to solve the transaction problem based on Mongo.
We need to add a version for each data to control the code directly:
Co (function *(){
For (var I = 0; I <3000; I ++ ){
While (1 ){
Var getTest = yield fetch CTest. findOne ({
"Name": "cb"
},
{
"Fields ":{
"_ Id": 0
}
});
GetTest. data = getTest. data + 1;
Var originalVer = getTest. ver;
GetTest. ver = getTest. ver + 1;
Console. log (getTest );
Var ret = yield fetch CTest. update ({
"Name": "cb ",
"Ver": originalVer
},
{
"$ Set": getTest
});
If (ret) break;
}
}
})();
The following is the expected result :)