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.