I currently have a setup with multiple requests to the database in a for-loop.
// week is a moment-range object
for (const day of week.by('day')) {
// get start and end of day
const startDay = day.startOf('day').toDate();
const endDay = day.endOf('day').toDate();
// I would like to reduce this query to one
const data = await Model.find({
$or: [
{
$and: [{ start: { $gte: startDay } }, { start: { $lt: endDay } }],
},
{
$and: [{ end: { $gte: startDay } }, { end: { $lt: endDay } }],
},
],
})
.sort({ start: 'asc' })
.select('_id someref')
.populate('someref', 'name');
console.log(data);
}
This is not very efficient and therefore I would like to reduce it to one query, grouped by the current return of data.
I've tried already to prepare the find parameter in the for-loop but didn't get far. Any hints would be very much appreciated.