I'm trying to check if there is a booking in a range of time. Not sure how to use the or condition in mongodb using mongoose.
Here is what I have:
const appoinments = await Appointment.find({
seller: seller._id,
startTime: {
$gt: ISODate(new Date(req.body.startTime).toISOString),
$lt: ISODate(new Date(req.body.endTime).toISOString),
},// I WANT TO ADD THE OR TO THIS TWO QUERIES
endTime: {
$gt: ISODate(new Date(req.body.startTime).toISOString),
$lt: ISODate(new Date(req.body.endTime).toISOString),
},
});
I want to check and find for any appointment that conflict with new appointment that is about to be added or any appointment that ends during that time of the appointment.
Here is what my Appointment looks like:
const appointmentSchema = new mongoose.Schema({
seller: {
type: mongoose.Schema.Types.ObjectId,
ref: "Seller",
},
startTime: {
type: Date,
required: true,
},
endTime: {
type: Date,
},
});
CodePudding user response:
You can simply use the or()
member function that mongoose provides. It works just like the $or
operator defined in the mongoose documentation.
I hope it helped!
const appoinments = await Appointment.find().or([
{
startTime: {
$gt: ISODate(new Date(req.body.startTime).toISOString),
$lt: ISODate(new Date(req.body.endTime).toISOString),
}
},
{
endTime: {
$gt: ISODate(new Date(req.body.startTime).toISOString),
$lt: ISODate(new Date(req.body.endTime).toISOString),
},
}
]);