diff --git a/Server/models/Check.js b/Server/models/Check.js index f4c3c35d4..0b46b4315 100644 --- a/Server/models/Check.js +++ b/Server/models/Check.js @@ -34,39 +34,43 @@ const CheckSchema = mongoose.Schema( CheckSchema.pre("save", async function (next) { try { const monitor = await mongoose.model("Monitor").findById(this.monitorId); + if (monitor) { // Check if the monitor has notifications if (monitor.notifications && monitor.notifications.length > 0) { + // Only send email if monitor status has changed if (monitor.status !== this.status) { const emailService = new EmailService(); if (monitor.status === true && this.status === false) { - // Notify user that the monitor is down - const users = await mongoose.model("User").find({ _id: monitor.userId }); - if (users.length > 0) { - const user = users[0]; - await emailService.buildAndSendEmail( - "serverIsDownTemplate", - { monitorName: monitor.name, monitorUrl: monitor.url }, - user.email, - `Monitor ${monitor.name} is down` - ); + // Notify users that the monitor is down + for (const notification of monitor.notifications) { + if (notification.email) { + await emailService.buildAndSendEmail( + "serverIsDownTemplate", + { monitorName: monitor.name, monitorUrl: monitor.url }, + notification.email, + `Monitor ${monitor.name} is down` + ); + } } } if (monitor.status === false && this.status === true) { - // Notify user that the monitor is up - const users = await mongoose.model("User").find({ _id: monitor.userId }); - if (users.length > 0) { - const user = users[0]; - await emailService.buildAndSendEmail( - "serverIsUpTemplate", - { monitorName: monitor.name, monitorUrl: monitor.url }, - user.email, - `Monitor ${monitor.name} is back up` - ); + // Notify users that the monitor is up + for (const notification of monitor.notifications) { + if (notification.email) { + await emailService.buildAndSendEmail( + "serverIsUpTemplate", + { monitorName: monitor.name, monitorUrl: monitor.url }, + notification.email, + `Monitor ${monitor.name} is back up` + ); + } } } + + // Update monitor status monitor.status = this.status; await monitor.save(); } @@ -80,4 +84,5 @@ CheckSchema.pre("save", async function (next) { }); + module.exports = mongoose.model("Check", CheckSchema);