Node. js atomic MongoDB instance tutorial

Source: Internet
Author: User
Tags findone mongodb

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 :)

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.