title: Mongodb upsert command in nodejs
body: <p>I have created a collection named Account.</p>
  
  <p>At first shot, I am inserting around 5 records.</p>
  
  <pre><code>{"Id":"0012800000C6Q19AAF","Name":"Aditya Kumar"}
  {"Id":"0012800000C6MldAAF","Name":"GenePoint"}
  {"Id":"0012800000C6MlbAAF","Name":"United Oil &amp; Gas, UK"}
  {"Id":"0012800000C6MlcAAF","Name":"United Oil &amp; Gas, Singapore"}
  {"Id":"0012800000C6MlTAAV","Name":"Edge Communications"}
  {"Id":"0012800000C6MlUAAV","Name":"Burlington Textiles Corp of America"}
  </code></pre>
  
  <p>I am bringing data from the external system, which has already an ID field associated with it.</p>
  
  <p>Again next time when a request comes for inserting extra 5 records, I want to check if Id field of upcoming records already exists in my MongoDB(if yes, then do an update else insert).</p>
  
  <p>And don't get confused by Id field coming from external system with _Id field created for every MongoDB document.</p>
  
  <p>Here is what I have tried:</p>
  
  <pre><code>var x= fields["data"]; obj='Account';
  db.createCollection(obj);
  
  db.collection(obj).insert(fields, function(err, doc) {
    if (err) {
      handleError(res, err.message, "Failed to create new contact.");
    } else {
      res.status(201).json(doc.ops[0]);
    }
  })
  </code></pre>