How to dynamically populate a Mongoose document document at runtime?

I have a schema that has a field that can refer to another schema.

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

The docs of this schema allow me to track changes in different objects typeswith objectId.

For example, if you Userchanged namefrom John to Steve, the document Historywould have:

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

Obviously, there typecan be many different things. My question is: can I magically populatenot know the objectId field typebefore the request?

I know that I can:

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

But this requires me to know what typeis there Userwhen building the request.

And, obviously, I can execute the second query manually with typeand objectId.

, ref ( ) ? , , .

+4

Source: https://habr.com/ru/post/1607772/


All Articles