title: Mongoose Update Document or Insert New Document if ID Is Not Found (Express REST API)
body: <p>I have set up a Express REST Api and would like to Implement a task that checks if a certain Object ID exists.</p>
  
  <p>If that ID exists in the Mongo Database I want to update this Document using a Put Request. This Part already works in my code.</p>
  
  <p>IF the ID does not yet exist in the database I would like to create a new Document. To do this I tried to set the "upsert" option to true, But If I now make a put request to a ID, which isn't in my DB yet it comes back with the error:</p>
  
  <pre><code>throw er; // Unhandled 'error' event
    ^
  CastError: Cast to ObjectId failed for value "34455ab67" at path "_id" for model "event"
  </code></pre>
  
  <p>Here is my Code for the event model:</p>
  
  <pre><code>var mongoose = require('mongoose');
  
  var eventSchema = mongoose.Schema({
     name: {
         type: String,
         required: true
     }
  });
  var Events = module.exports = mongoose.model('event', eventSchema, 'event');
  
  module.exports.updateEvent = function (id, event, options, callback) {
     var query = {_id : id};
     var update = {
         name: event.name,
     };
     Events.findOneAndUpdate(query, update, options, callback);
  };
  </code></pre>
  
  <p>This is the REST API Call</p>
  
  <pre><code>app.put('/api/event/:_id', function(req, res) {           
     var id = req.params._id;
     var event = req.body;
     var options = {
         upsert: true,
         new: true,
         setDefaultsOnInsert: true
     };
     Events.updateEvent(id, event, options, function(err, event){
         if(err){
             trow err;
         }
         res.json(event);
     })
  });
  </code></pre>
  
  <p>Any help would be highly appreciated! </p>