// Cache for site data (5 minutes TTL)
const siteCache = new Map();
const SITE_CACHE_TTL = 5 * 60 * 1000; // 5 minutes
const normDate = (d) => {
const x = new Date(d);
x.setHours(0, 0, 0, 0);
return x;
};
const dayIndex = (d) => new Date(d).getDay();
function* datesBetween(from, to) {
const s = normDate(from), e = normDate(to);
for (let d = new Date(s); d <= e; d.setDate(d.getDate() + 1))
yield new Date(d);
}
function genSpots(spotsPerHour, factor, offset, partialCount = null, fillOrder = "head") {
let arr = [];
if (factor === 0) {
for (let i = 1; i <= spotsPerHour; i++) arr.push(i);
} else {
const step = factor + 1;
const start = 1 + (offset || 0);
for (let i = start; i <= spotsPerHour; i += step) arr.push(i);
}
if (Number.isInteger(partialCount) && partialCount >= 0) {
arr = fillOrder === "tail" ? arr.slice(-partialCount) : arr.slice(0, partialCount);
}
return arr;
}
if (!fromDate || !toDate) throw new Error("fromDate and toDate are required");
if (!["spot", "slot"].includes(bookingType))
throw new Error('bookingType must be "spot" or "slot"');
if (![0, 1, 2].includes(factor)) throw new Error("factor must be 0|1|2");
if (!Array.isArray(siteIds) || siteIds.length === 0)
throw new Error("siteIds must be a non-empty array");
if (!Array.isArray(daily) || daily.length === 0)
throw new Error("daily patterns are required");
if ((bookingType === "slot" || bookingType === "spot") &&
!(Number.isInteger(numberOfSlots) && numberOfSlots > 0)) {
throw new Error("numberOfSlots must be a positive integer for slot and spot bookings");
}
if (!(offset === "auto" || (Number.isInteger(offset) && offset >= 0 && offset <= factor))) {
throw new Error('offset must be "auto" or an integer 0..factor');
}
if (!["head", "tail"].includes(fillOrder))
throw new Error('fillOrder must be "head" or "tail"');
for (const p of daily) {
if (!Array.isArray(p.days) || p.days.length === 0)
throw new Error("each daily pattern needs days[]");
if (![p.startHour, p.endHour].every(h => Number.isInteger(h) && h >= 0 && h <= 23)) {
throw new Error("startHour/endHour must be 0..23");
}
if (![p.startMinutes, p.endMinutes].every(m => Number.isInteger(m) && m >= 0 && m < 60)) {
throw new Error("startMinutes/endMinutes must be 0..59");
}
if (!Number.isInteger(p.duration) || p.duration <= 0)
throw new Error("duration (minutes) required");
}
// Create nested lookup map for conflicts
const conflictMap = new Map();
conflicts.forEach(conflict => {
const siteKey = ${conflict.siteId}-${conflict.bookingDate.toISOString()};
if (!conflictMap.has(siteKey)) {
conflictMap.set(siteKey, new Map());
}
code
const slotHourKey = `${conflict.slotNumber}-${conflict.hour}`;
if (!conflictMap.get(siteKey).has(slotHourKey)) {
conflictMap.get(siteKey).set(slotHourKey, new Set());
}
conflictMap.get(siteKey).get(slotHourKey).add(conflict.spotNumber);
});
return conflictMap;
}
// OPTIMIZED: Process all slots for a site-date combination
function findFreeSlots(takenSlots, totalSlots, numberOfSlots) {
const available = [];
for (let slot = 1; slot <= totalSlots; slot++) {
if (!takenSlots || !takenSlots.has(slot)) {
available.push(slot);
if (available.length === numberOfSlots) break;
}
}
return available;
}
// OPTIMIZED: Main plan building function
async function buildPlanOptimized(body) {
const settings = validatePayload(body);
const { bookingType, factor, offset, siteIds, numberOfSlots, allOrNothing, fillOrder } = settings;
// Get sites with caching
const sites = await getSitesOptimized(siteIds);
if (sites.length !== siteIds.length) throw new Error("Some siteIds not found");
for (const date of dates) {
if (isSlotBooking) {
// For slot bookings, book all spots for all hours
const spotsPerHour = spotsData.spotsPerHour || 30;
for (let hour = 0; hour < 24; hour++) {
for (let spotNumber = 1; spotNumber <= spotsPerHour; spotNumber++) {
allDocs.push({
bookingId,
siteId,
bookingDate: date,
slotNumber,
hour,
spotNumber,
});
}
}
} else {
// For spot bookings, book specific spots for specific hours
for (const spotDetail of spotsData) {
if (spotDetail.slotNumber === slotNumber) {
for (const spot of spotDetail.spots) {
allDocs.push({
bookingId,
siteId,
bookingDate: date,
slotNumber: spotDetail.slotNumber,
hour: spotDetail.hour,
spotNumber: spot,
});
}
}
}
}
}
// Batch insert all documents at once
if (allDocs.length > 0) {
const batchSize = 1000; // Insert in batches to avoid memory issues
for (let i = 0; i < allDocs.length; i += batchSize) {
const batch = allDocs.slice(i, i + batchSize);
await BookingSpot.insertMany(batch, { ordered: false });
}
}
}
// OPTIMIZED: Create booking records in batches
async function createBookingRecordsOptimized(bookingMetadataId, settings, sites, planBySite) {
const { fromDate, toDate, bookingType, factor, daily, status, jnumbers, agentId, createdBy, client } = settings;
for (const sitePlan of planBySite) {
const site = sites.find(s => s._id.toString() === sitePlan.siteId.toString());
if (!site) continue;
code
for (let pIdx = 0; pIdx < daily.length; pIdx++) {
const sample = daily[pIdx];
const relatedBookings = sitePlan.bookings.filter(b => b.patternIdx === pIdx);
if (relatedBookings.length === 0) continue;
// Collect all unique slots for this pattern
const allSlots = new Set();
relatedBookings.forEach(booking => {
if (bookingType === "slot") {
(booking.slotsBooked || []).forEach(slot => allSlots.add(slot));
} else {
(booking.spotPlans || []).forEach(plan => allSlots.add(plan.slotNumber));
}
});
// Create booking records for each slot
for (const slotNumber of allSlots) {
const bookingDoc = {
bookingMetadataId,
fromDate, toDate, bookingType, factor,
days: sample.days,
startHour: sample.startHour,
startMinutes: sample.startMinutes,
endHour: sample.endHour,
endMinutes: sample.endMinutes,
startTime: sample.startTime,
endTime: sample.endTime,
duration: sample.duration,
numberOfSlots: 1,
status,
jnumber: jnumbers[0] || "",
siteId: String(sitePlan.siteId),
agentId, createdBy, client,
slotNumber,
};
bookingDocs.push(bookingDoc);
}
}
}
// Batch insert all booking records
const createdBookings = await Booking.insertMany(bookingDocs);
// Create booking spots in parallel
let bookingIndex = 0;
for (const sitePlan of planBySite) {
const site = sites.find(s => s._id.toString() === sitePlan.siteId.toString());
if (!site) continue;
// First check availability (optimized)
const plan = await buildPlanOptimized(req.body);
if (!plan.success) {
console.timeEnd('createBooking');
return res.status(409).json({
success: false,
error: "All-or-nothing violated",
details: plan,
});
}
const settings = validatePayload(req.body);
console.log("Creating booking with optimized process");
// Create metadata record
console.time('createMetadata');
const meta = await BookingMetadata.create({
fromDate: settings.fromDate,
toDate: settings.toDate,
bookingType: settings.bookingType,
factor: settings.factor,
daily: settings.daily,
numberOfSlots: settings.numberOfSlots,
status: settings.status,
jnumbers: settings.jnumbers,
siteIds: settings.siteIds,
comments: settings.comments,
agentId: settings.agentId,
createdBy: settings.createdBy,
client: settings.client,
});
console.timeEnd('createMetadata');
// Get sites (cached)
const sites = await getSitesOptimized(settings.siteIds);
// Create all booking records and spots in batches
console.time('createBookingRecords');
await createBookingRecordsOptimized(meta._id, settings, sites, plan.planBySite);
console.timeEnd('createBookingRecords');
console.timeEnd('createBooking');
return res.json({ success: true, plan });
} catch (err) {
console.error('createBooking error:', err);
return res.status(400).json({ success: false, error: err.message });
}
},
};
when i have 2 -3 month booking it's create 1M+ records in bookingspot table and Api is also taking 7 to 10 min
can we change database schema and still archive same thing but very optimize way
You're currently dealing with a massive data volume (1M+ records) and long processing times (7–10 minutes) when handling multi-month bookings. This is largely due to:
Granular data modeling: You're storing every individual spot in a separate document.
High write volume: For every hour and every spot, you're inserting a new document.
Redundant data: Each BookingSpot record is a single spot per hour per day.
✅ Goal
You want to:
Reduce the number of documents inserted per booking.
Maintain the same functionality (availability checks, reporting, etc.).
Improve performance (both write and read).
Still allow for conflict checking and querying by spot/hour/slot.
🧠 Solution Overview
✅ Option 1: Optimize Schema by Storing Spots as Arrays
Instead of inserting one document per spot, store spot usage per hour per slot per day in a single document.
✅ Option 2: Use Time-Series Collections (MongoDB 5.0+)
If you're using MongoDB 5.0 or higher, you can use time-series collections to optimize time-based data.