title: Is it possible to have mongoose populate a Mixed field only if the field contains an ObjectId?
body: <h1>Setup</h1>
  
  <p>Let's say we have schemas for <code>Foo</code> and <code>Bar</code>. <code>Foo</code> has a field <code>bar</code>. This field can either contain an ObjectId that reference a document <code>Bar</code>, or it could contain other arbitrary objects that are not ObjectIds.</p>
  
  <pre><code>const fooSchema = new mongoose.Schema({
    bar: {
      type: mongoose.Schema.Types.Mixed,
      ref: 'Bar'
    }
  });
  const Foo = &lt;any&gt;mongoose.model&lt;any&gt;('Foo', fooSchema);
  
  const barSchema = new mongoose.Schema({
    name: String
  });
  const Bar = &lt;any&gt;mongoose.model&lt;any&gt;('Bar', barSchema);
  </code></pre>
  
  <h1>Problem</h1>
  
  <p>Now suppose we have a bunch of <code>Foo</code> documents. </p>
  
  <p>I would like to be able to use mongoose's <a href="http://mongoosejs.com/docs/populate.html" rel="noreferrer"><code>populate</code></a> on the <code>bar</code> field to automatically replace references to a <code>Bar</code> document with the actual <code>Bar</code> document itself. I would also like to leave all other objects that are not references to a <code>Bar</code> document unchanged.</p>
  
  <p>Normally, I would use something like this to get all the <code>Foo</code> documents and then populate the <code>bar</code> field:</p>
  
  <pre><code>Foo.find().populate('bar')
  </code></pre>
  
  <p>However, this method will throw an exception when it encounters objects in the <code>bar</code> field that are not ObjectIds, as opposed to leaving them untouched.</p>
  
  <blockquote>
    <p>UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): CastError: Cast to ObjectId failed for value "Some arbitrary object" at path "_id" for model "Bar"</p>
  </blockquote>
  
  <h1>Attempt at finding a solution</h1>
  
  <p>I have examined using the <code>match</code> option on <code>populate</code>, by requiring that a field on <code>Bar</code> exists:</p>
  
  <pre><code>Foo.find().populate({
    path: 'bar',
    match: {
      name: {
        $exists: true
      }
    }
  }
  </code></pre>
  
  <p>Unfortunately, the error is the same.</p>
  
  <h1>Question</h1>
  
  <p>So my question is then, is there any way to get mongoose to only <code>populate</code> a field if the field contains an ObjectId, and leave it alone otherwise?</p>