I have a Typescript project using mongoose that has a virtual that depends on a field that has been populated from a middleware function. I am having some trouble figuring out how to type things properly.
const UserSchema = new Schema({
someid: String,
email: String,
roles: {
type: Schema.Types.ObjectId,
ref: 'Role'
}
)}
UserSchema.pre<Query>(/^find/, autopopulate);
function autopopulate(next){
this.populate('roles'); // I assume at runtime the roles field is overwritten to be an array of `RoleInterface` objects, rather than an array of ObjectIds. How does Typescript deal with this?
next();
}
UserSchema.virtual('isAdmin').get(function () {
return this.roles[1].name === 'admin'; //this.roles is [{_id: ObjectId}] as defined in the schema, so this fails the typecheck
});
The issue is that name is not a field of role in the schema as written, it's a field in the populated version of the schema from the pre hook. What is the correct way to type things so that this will work?