Add conditional to avoid extra db operatons

This commit is contained in:
Alex Holliday
2024-07-03 11:46:30 -07:00
parent 9ccf42fe55
commit 031ae06d41

View File

@@ -31,20 +31,26 @@ const CheckSchema = mongoose.Schema(
}
);
/**
* When a check is created, we should update the stauts of the associated monitor
* if it has changed. Monitor starts with default status: true
*/
CheckSchema.pre("save", async function (next) {
const monitor = await mongoose.model("Monitor").findById(this.monitorId);
if (monitor.status !== this.status) {
if (monitor.status === true && this.status === false) {
// TODO issue alert
console.log("Monitor went down");
}
if (monitor.status === true && this.status === false) {
console.log("Monitor went down");
if (monitor.status === false && this.status === true) {
// TODO issue alert
console.log("Monitor went up");
}
await monitor.save();
}
if (monitor.status === false && this.status === true) {
console.log("Monitor went up");
}
monitor.status = this.status;
await monitor.save();
next;
});