title: Mongoose Population: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"
body: <p>Running into a <code>CastError</code> in Mongoose when populating nested ObjectId references (value <code>{}</code>) that are apparently <em>valid</em>, to the extent that they're not blocked when saving to schema.</p>
  
  <p>Interested in resolving this on the server-side to prevent malformed data in future, however, I understand not saving these values from the client would be a good idea. The fact that an empty object <em>can</em> be saved to a Mongoose schema with <code>type: mongoose.Schema.Types.ObjectId</code> and later throws a <code>CastError</code> using population is my primary concern.</p>
  
  <p>Example data:</p>
  
  <pre><code>// representation of data in model
  {
      "_id": /* ObjectId */,
      "refA": {} // empty object,
      "refB": /* ObjectId */,
      "refC": /* ObjectId */
  }
  </code></pre>
  
  <p>Example method:</p>
  
  <pre><code>// mongoose query with population
  function populator(id, cb) {
      // find by string or object id
      var query = Schema.findById(id);
  
      // population of query
      query.populate({
          // string of fields to expand
          path: 'refA refB refC',
          // option to include virtuals
          options: {toJSON: {virtuals: true}}
      });
  
      // return executed query,
      // optional callback
      return _.isFunction(cb) ? query.exec(cb) : query.exec();
  }
  </code></pre>
  
  <p>Resulting error:</p>
  
  <pre><code>// error in console
  { [CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"]
      message: 'Cast to ObjectId failed for value "[object Object]" at path "_id"',
      name: 'CastError',
      type: 'ObjectId',
      value: {},
      path: '_id' }
  </code></pre>
  
  <p>Could this be considered a bug in Mongoose?</p>
  
  <h3>Edit:</h3>
  
  <p>Mongoose is allowing <code>{}</code> to be saved to the above schema.</p>
  
  <p>Example schema:</p>
  
  <pre><code>var schema = mongoose.Schema(mongoose.Schema{
      "refA": {type: mongoose.Schema.Types.ObjectId, ref: 'ReferenceA'},
      "refB": {type: mongoose.Schema.Types.ObjectId, ref: 'ReferenceB'},
      "refC": {type: mongoose.Schema.Types.ObjectId, ref: 'ReferenceC'}
  });
  </code></pre>
  
  <p>Method handling PUT:</p>
  
  <pre><code>var id = /* existing document */,
      body = {"refA": {}};
  
  query = Table.findByIdAndUpdate(id, {$set: body}).lean();
  query.exec(function(err, record) { /* ... */ });
  </code></pre>
  
  <p>It's determined that Mongoose shouldn't allow <code>{}</code> to be saved as an ObjectId type. Haven't tested doing so when saving a new document / handling a POST.</p>