title: Mongoose populate either ObjectId reference or String
body: <p>Is there a way to specify a heterogeneous array as a schema property where it can contain both ObjectIds and strings? I'd like to have something like the following:</p>
  
  <pre><code>var GameSchema = new mongoose.schema({
      players: {
          type: [&lt;UserModel reference|IP address/socket ID/what have you&gt;]
      }
  </code></pre>
  
  <p>Is the only option a <code>Mixed</code> type that I manage myself? I've run across <a href="http://mongoosejs.com/docs/discriminators.html" rel="nofollow noreferrer">discriminators</a>, which look somewhat promising, but it looks like it only works for subdocuments and not references to other schemas. Of course, I could just have a <code>UserModel</code> reference and create a <code>UserModel</code> that just stores the IP address or whatever I'm using to identify them, but that seems like it could quickly get hugely out of control in terms of space (having a model for every IP I come across sounds bad).</p>
  
  <p>EDIT:</p>
  
  <p>Example:</p>
  
  <p>A game has one logged in user, three anonymous users, the document should look something like this:</p>
  
  <pre><code>{ players: [ ObjectId("5fd88ea85...."), "192.0.0.1", "192.1.1.1", "192.2.2.1"] }
  </code></pre>
  
  <p>Ideally this would be populated to:</p>
  
  <pre><code>{ players: [ UserModel(id: ..., name: ...),  "192.0.0.1", "192.1.1.1", "192.2.2.1"] }
  </code></pre>
  
  <p>EDIT:</p>
  
  <p>I've decided to go a different route: instead of mixing types, I'm differentiating with different properties. Something like this:</p>
  
  <pre><code>players: [
      {
          user: &lt;object reference&gt;,
          sessionID: &lt;string&gt;,
          color: {
             type: String
          },
          ...other properties...
      }
  ]
  </code></pre>
  
  <p>I have a validator that ensures only one of <code>user</code> or <code>sessionID</code> are populated for a given entry. In some ways this is more complex, but it does obviate the need to do this kind of conditional populating and figuring out what type each entry is when iterating over them. I haven't tried any of the answers, but they look promising.</p>