title: How can I create/find in Mongoose?
body: <p>Sometimes I need a document to exist in the DB, and am happy to either work with the existing document, or create the document if it's missing, and work with the new one.</p>
  
  <p>This seems like a fairly common use case, but I've looked through the <a href="http://mongoosejs.com/docs/api.html" rel="noreferrer">Mongoose docs</a> and I can't find anything.</p>
  
  <p>Mongoose Collection methods like <code>findOneAndUpdate()</code> and <code>update()</code> with <code>upsert: true</code> are about modifying documents - I don't wish to modify the document if it exists, just get a reference to it. </p>
  
  <p><strong>Example</strong>: (added for @neillunn) I want to add a User with a reference to a Company whose 'name' is 'foo'. Before that, I'd like to lookup a Company with <code>{name: 'foo'}</code> and create that if it doesn't exist.</p>
  
  <p><strong>Example 2</strong>: (added for @neillunn) code I'm using now to handle the example scenario:</p>
  
  <pre><code>// Find or create an an instance and return a cb with a reference to it.
  var findOrCreate = function(model, criteria, cb){
      model.update(criteria, criteria, {upsert: true}, function(err, numberAffected, raw){
          if ( ! raw.updatedExisting ) {
              console.log('Created instance')
          } else {
              console.log('Found existing instance')
          }           
          model.findOne(criteria, cb)
      })
  }
  </code></pre>
  
  <p><strong>Note</strong>: <code>findOneAndUpdate()</code> won't work because it will try and modify the existing document, and get a 'duplicate key error index'  </p>