title: Upsert Document and/or add a Sub-Document
body: <p>I've been wrestling with the asynchronous nature of MongoDB, Mongoose and JavaScript and how to best make multiple updates to a collection.</p>
  
  <p>I have an Excel sheet of client and contact data.  There are some clients with multiple contacts, one per line, and the client data is the same (so the client name can be used as a unique key - in fact in the schema it's defined with <code>unique: true</code>).</p>
  
  <p>The logic I want to achieve is:</p>
  
  <ol>
  <li>Search the Client collection for the client with <code>clientName</code> as the key</li>
  <li>If a matching clientName isn't found then create a new document for that client (not an upsert, I don't want to change anything if the client document is already in the database)</li>
  <li>Check to see if the contact is already present in the array of contacts within the client document using <code>firstName</code> and <code>lastName</code> as the keys</li>
  <li>If the contact isn't found then <code>$push</code> that contact onto the array</li>
  </ol>
  
  <p>Of course, we could easily have a situation where the client doesn't exists (and so is created) and then immediately, the very next row of the sheet, is another contact for the same client so then I'd want to find that existing (just created) client and <code>$push</code> that 2nd new contact into the array.</p>
  
  <p>I've tried this but it's not working:</p>
  
  <pre><code>Client.findOneAndUpdate(
    {clientName: obj.client.clientname},
    {$set: obj.client, $push: {contacts: obj.contact}},
    {upsert: true, new: true},
    function(err, client){
      console.log(client)
    }
  )
  </code></pre>
  
  <p>and I've had a good look at other questions, e.g.:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/17774929/create-mongodb-document-with-subdocuments-atomically">create mongodb document with subdocuments atomically?</a></li>
  <li><a href="https://stackoverflow.com/questions/28026197/upserting-complex-collections-through-mongoose-via-express">https://stackoverflow.com/questions/28026197/upserting-complex-collections-through-mongoose-via-express</a></li>
  </ul>
  
  <p>but can't get a solution... I'm coming to the conclusion that maybe I have to use some app logic to do the find, then decisions in my code, then writes, rather than use a single Mongoose/Mongo statement, but then the issues of asynchronicity rear their ugly head.</p>
  
  <p>Any suggestions?</p>