Mongoose .pre('save') does not trigger
Use pre('validate')
instead of pre('save')
to set the value for the required field. Mongoose validates documents before saving, therefore your save
middleware won't be called if there are validation errors. Switching the middleware from save
to validate
will make your function set the number field before it is validated.
quotesSchema.pre('validate', true, function(next) {
Setting.findByIdAndUpdate(currentSettingsId, { $inc: { nextQuoteNumber: 1 } }, function (err, settings) {
if (err) { console.log(err) };
this.number = settings.nextQuoteNumber - 1; // substract 1 because I need the 'current' sequence number, not the next
next();
});
});