I want to be able to save a RegUser (registered user) to the MongoDB RegUsers collection only IF the email domain provided exists in the Firm collection. I have a pre-save hook that validates the email domain but I do not know what command/function to call to cancel the save if the email domain does not exist. Is there a better way to accomplish this or what command should I call?
** registered-user.ts **:
regUserSchema.pre('save', async function(done) {
const domain = this.email.split('@')[1];
const exists = await Firm.findOne({ domain });
if (exists) {
done();
} else {
// WHAT TO DO HERE??
}
});
CodePudding user response:
In order to stop the continuation of the hooks and the actual update mongoose
excepts you to throw an error, you might need to add error handling to your code depending on how it's written.
if (exists) {
done();
} else {
throw new Error('firm does not exist')
}