refactor(monitors): optimize bulkTogglePause from 3 to 2 DB queries

Use find + updateMany with timestamps:false instead of find IDs +
updateMany + fetch updated. Manually set updatedAt and edit
in-memory documents to avoid a third DB round trip.

Fixes #3602
This commit is contained in:
harsh-aghara committed 2026-05-05 23:43:06 +05:30
1 parent e725128b10
commit ba2d23fd82
1 file changed
+14 -11
@@ -241,22 +241,25 @@ class MongoMonitorsRepository implements IMonitorsRepository {
teamId: new mongoose.Types.ObjectId(teamId), teamId: new mongoose.Types.ObjectId(teamId),
isActive: pause, // Only pause if active (true), only resume if inactive (false) isActive: pause, // Only pause if active (true), only resume if inactive (false)
}; };
const nextStatus = pause ? "paused" : "initializing";
const eligibleIds = (await MonitorModel.find(filter).select("_id").lean()).map((doc) => doc._id); const eligible = await MonitorModel.find(filter);
if (eligibleIds.length === 0) return []; if (eligible.length === 0) return [];
const now = new Date();
await MonitorModel.updateMany( await MonitorModel.updateMany(
{ _id: { $in: eligibleIds } }, { _id: { $in: eligible.map((doc) => doc._id) } },
{ { $set: { isActive: !pause, status: nextStatus, updatedAt: now } },
$set: { { timestamps: false }
isActive: !pause,
status: pause ? "paused" : "initializing",
},
}
); );
const updatedMonitors = await MonitorModel.find({ _id: { $in: eligibleIds } }); eligible.forEach((doc) => {
return this.mapDocuments(updatedMonitors); doc.isActive = !pause;
doc.status = nextStatus;
doc.updatedAt = now;
});
return this.mapDocuments(eligible);
}; };
deleteById = async (monitorId: string, teamId: string) => { deleteById = async (monitorId: string, teamId: string) => {