title: How to prevent MongoDB from creating multiple records due to async
body: <p>My app is becoming a bit of a nightmare and this is a non-standard MongoDB problem I've not been able to find elsewhere.</p>
  
  <p>My server flow is like this:</p>
  
  <ol>
  <li>A user uploads a list of objects containing <code>{names, emails and company domains}</code> to my server</li>
  <li>My server turns all of these into <code>Person</code> objects.</li>
  <li>Once the <code>Person</code> has been saved, I search MongoDB to see whether a record for the person's <code>Domain</code> exists.</li>
  <li>If it exists, I add the <code>Person</code>'s Mongo <code>_id</code> to a list of users from that <code>Domain</code>.</li>
  <li>If it doesn't exist, I create a new <code>Domain</code> document and save it.</li>
  </ol>
  
  <p>This works in theory, BUT, due to Async, sometimes I'm sending thousands of <code>Person</code> objects to the Domain saver function at once. Which means (at least, what I think is happening):</p>
  
  <ul>
  <li>Mongo searchers for "domain 1", sees there is no document so creates one, then saves one.</li>
  <li>While this is still happening,Mongo searches for "Domain 1" from a separate user. No document has been saved yet so it finds none and makes a new one.</li>
  <li>Now I have two documents with the same Domain identifier.</li>
  </ul>
  
  <p>Here's the code I'm currently using:</p>
  
  <pre><code>Domain.findOne({
    domain: domn
  }, function(err, rec) {
    if (err) {
      console.log("Domain finding error: " + err)
      bigCount.doneDoms++;
      checkCount()
    } else if (rec){
      var tempObj = {}
          tempObj['$addToSet'] = { users: id }
          tempObj['$addToSet'].emails = user.email;
  
      if (userDoms.indexOf(rec._id) === -1) {
        userDoms.push(rec._id)
      }
  
      Domain.update({domain: domn}, tempObj, function(err) {
        if (err) {
          console.log("Old rec save Error: " + err)
          bigCount.doneDoms++;
          checkCount();
        }else{
           // Saved Document
        }
      });
  
    } else { 
      var newDom = new Domain();
      newDom.domain = user.domain;
      newDom.company = user.company;
      newDom.users = [];
      newDom.users.push(id);
      newDom.emails = [];
      newDom.emails.push(user.email);
  
      newDom.save(function(err, record) {
        if (err) {
          console.log("Dom save error: " + err)
        } else {
          // Saved Document
        }
      });
  
    }
  })
  </code></pre>
  
  <p>Perhaps a stripped-down version of the question is, how do I handle somethign like this:</p>
  
  <pre><code>var arr = [{dom: 'dom1.com', user: 'James'}, {dom: 'dom1.com', user: "Phil"}, {dom: 'dom1.com', user: "Jess"} ...x1000... {dom: 'dom1.com', user: "Chris"];
  
  for(var i - 0; i&lt; arr.length; i++){
    var dom = arr[i]; var user = arr[i].user;
    Domain.findOne({domain: dom}, function(err, rec){
      if(rec){
        // Update old rec
        if(rec.users.indexOf(user) === -1){
           rec.users.push(user);
        }
        rec.save();
      ]else{
  
       // Make a new rec
       var rec = New Domain();
       rec.users = [user]
       rec.save();
      }
    })
  }
  </code></pre>
  
  <p>Due to speed/Async, a lot of records are going to be created here, when really I only one want </p>