Reputation: 34
This is probably an embarrassing question but I'm attempting to render a user search based on both location searching & date. Our profile object is structed as follows;
availability: {
monday: { type: Boolean, default: false },
tuesday: { type: Boolean, default: false },
wednesday: { type: Boolean, default: false },
thursday: { type: Boolean, default: false },
friday: { type: Boolean, default: false },
saturday: { type: Boolean, default: false },
sunday: { type: Boolean, default: false },
}
Here is my controller;
exports.findUsersByDay = asyncHandler(async (req, res) => {
const search = req.params.search;
try {
const profileList = await Profile.find({
availability: { $in: search }
});
if (profileList.length > 0) {
return res.status(200).json({ profiles: profileList });
} else {
return res.status(404).json({ message: "No Profiles Found" });
}
} catch (error) {
return res.status(500).json({ message: error });
}
})
How Can I query whether the profile object has one of the dates (or multiple if passed down as an array) to true?
Upvotes: 0
Views: 32
Reputation: 20461
You could create a dynamic query for this. Get all the days you wand and use it along with $and :
let findQuery = { $and : [ ]};
let search = ['monday','thursday']; search.forEach((a)=>{
let aName = `availability.${a}`
findQuery['$and'].push({
[aName] : true
})});
const profileList = await Profile.find(findQuery);
I think something similar could be done using $where too, but performance will take a hit.
Upvotes: 1