4

I have a schema that has a field that could reference different schema.

var HistorySchema = new Schema({
  type: {type: String, required: true},
  objectId: {
    type: Schema.Types.ObjectId,
    required: true,
  },
  changed: {type: Schema.Types.Mixed}
})

The documents of this schema allows me to keep track of changes happens in different types of objects with objectId.

For example, if User has changed name from 'John' to 'Steve', a History document would have:

{
    type: 'User',
    objectId: '55fa6bf0831ba3fa0879e7e8',
    changed: {name: {oldValue: 'John', newValue: 'Steve'}}
}

Obviously, type can be many different things. My question is, can I magically populate the objectId field without knowing type before the query?

I know I can do:

History.query({...}).populate('objectId', null, 'User').exec(...);

But that requires me to know the type is User when the query is constructed.

And obviously I can do a second query manually given the type and objectId.

For example, is it possible to save the ref type of a document (not schema) at runtime and take advantage of that? I look around and don't seem to find a way.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
yuklai
  • 1,595
  • 1
  • 14
  • 26
  • If you added the model name of `objectId` as another field in your schema, you should be able to do something automatic using post find [middleware](http://mongoosejs.com/docs/middleware.html). – JohnnyHK Sep 17 '15 at 12:58
  • Yes, as illustrated above, the modelName is `type`. – yuklai Sep 17 '15 at 16:51
  • 1
    Duh, don't know how I missed that. :) Then you should be all set to be able to do this in post find middleware by using [`Model.populate`](http://mongoosejs.com/docs/api.html#model_Model.populate). – JohnnyHK Sep 17 '15 at 17:32

0 Answers0