I have this schema where discriminator is defined by the type field.
const FilledSchema = new mongoose.Schema({
template:{ type: mongoose.SchemaTypes.ObjectId, ref: 'Template'},
user_id: mongoose.SchemaTypes.ObjectId,
type: String,
}, {discriminatorKey: 'type'});
The type field isn't ready until this function is completed:
FilledSchema.pre('validate', function(next) {
var data= this;
this.populate('template', function(err, res) {
if (err) next(err);
if (res.template === null) next('Template not found.');
data.type = res.template_id.type;
next();
});
})
After doing some tests I noticed that the discriminatorKey gets a value (null) before the pre middleware is run. How can I set the value to the discriminatorKey after I populate the "template" field?
question from:https://stackoverflow.com/questions/65943671/mongoose-run-function-before-setting-discriminatorkey