I am having some trouble using model.find to return a list of documents that match a variable condition within my nested schema. I am using node, express, and mongoose for this project.
Ideally I want to use a variable as the object key within the query so I can dynamically grab the day of the week and check the open hours. I haven't had any success so far in finding an answer for this online.
Here is my model.
const restaurantSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: { type: String, required: true },
coordinates: {
latitude: { type: Number, required: true },
longitude: { type: Number, required: true }
},
happy_hour: {
sunday: {
open: { type: Boolean },
open_at: { type: Number },
close_at: { type: Number }
},
monday: {
open: { type: Boolean },
open_at: { type: Number },
close_at: { type: Number }
},
tuesday: {
open: { type: Boolean },
open_at: { type: Number },
close_at: { type: Number }
},
wednesday: {
open: { type: Boolean },
open_at: { type: Number },
close_at: { type: Number }
},
thursday: {
open: { type: Boolean },
open_at: { type: Number },
close_at: { type: Number }
},
friday: {
open: { type: Boolean },
open_at: { type: Number },
close_at: { type: Number }
},
saturday: {
open: { type: Boolean },
open_at: { type: Number },
close_at: { type: Number }
}
}
});
Here is a snippet from the controller that is handling the logic for this express route. The snippet below has a static key called "Friday", but I want to dynamically get the day of the week and pass that in as a variable, something like $friday: { open: true } or what not.
exports.search = (req, res, next) => {
const radius = req.query.radius || 5;
const latitude = req.query.latitude;
const longitude = req.query.longitude;
const day = date.get_day();
const minutes = date.get_minutes();
console.log(query[day]);
if ( latitude == undefined || longitude == undefined ) {
res.status(404).json({
message: "Missing longitude or latitude"
})
}
Restaurant.find({
hours: {
friday: {
open: true
}
}
})
.exec()
.then(results => {
res.status(200).json({
data: results.map( result => {
query = JSON.parse("{hours: {``$day``: {open: true}}}")$dayin that statement. How does that work?