title: How to _update_ Mongo object inside array if object exists, add it to array if it doesn't?
body: <p>I'm learning Mongo and I've encountered a tricky problem.  It's for a class, so although this might be easier with Mongoose (or may not), we're supposed to do it with Mongo.</p>
  
  <p>I'm making a simple app to handle contacts for a variety of users.  The collection will have an array of various users, each of which will have an array of contacts, and those contact arrays will contain an array of objects with various strings.  </p>
  
  <pre><code>  users: [
      user: {
        contacts: [
         contact: {
               name:"a string"
                 }
                ]
            }
  
        ]
  </code></pre>
  
  <p>What I want to do is to have a function <code>updateContact</code> to which I will pass the <code>username</code> and a <code>contact</code> object.  The function will add a contact to a user's <code>contacts</code> array if and only if there is no match on the <code>name</code> field for that contact, but if there is a match on the <code>name</code> field will update the information in the matched contact object. </p>
  
  <p>I can figure out how to add the new <code>contact</code> but not how to check if it exists in the array and perform a merge in that case.  </p>
  
  <p>I have </p>
  
  <pre><code> return this._users.findOne({username})
              .then(user =&gt; {
                  if (!user) throw new LogicError(`user ${username} does not exist`)
                  return this._users.updateOne(
                      user,
                      {$push: {"contacts": contact}}
                  )
  
              })
  </code></pre>
  
  <p>My thought was to do a check first with <code>findOne</code> to see if the <code>contact</code> already exists in the array, and only add it with the above code if it is missing, but I don't know how to handle the case when it doesn't exist -- that is, if I'm using Promises, do I put the "add" code above in a <code>catch</code>?</p>
  
  <p>I feel sure there must be a way to solve this issue, and I've been combing Stack Overflow but haven't found a solution.  Any help much appreciated!</p>