简体   繁体   中英

Mongoose: Reduce from many queries to one

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.

Your query seems to find records that either start or end in a given day. As week is a range of consecutive days, this really translates to a query for records that either start in that week , or end in that week .

So you could remove the for loop, and define startDay and endDay as the start/end of the week, as follows:

const startDay = week.start.startOf('day').toDate();
const endDay = week.end.endOf('day').toDate();

The rest of your code can remain as it is. Just remove the line with for and the corresponding ending brace.

One difference though is that you wouldn't get any duplicates any more. In your current code you would get records that both start and end in the week (but not on the same day) twice . That will not happen with this code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM