简体   繁体   中英

How to write an or statement in mongodb using the find function in mongoose

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,
      },
  });

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),
        },
    }
]);

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