retrieve object in array with condition mongodb

Viewed 88

i have a MONGODB database to places like Restaurant Or Cafe and each place have an Array Of Object with name TABLES and each object has Number of table, and Array of booking Dates and details user can book any table by date and time so i want to check available tables and return the table that not booked in this time that user wants to book..

HERE IS MY SCHEMA FOR TABLES ARRAY

tables: [
      {
        num: Number,
        isBooked: {
          type: Boolean,
          default: false,
        },
        bookings: [
          {
            User: {
              type: mongoose.Schema.Types.ObjectId,
              ref: "Users",
            },
            Name: {
              type: String,
            },
            Date: {
              type: String,
            },
            Time: {
              type: String,
            },
            Note: {
              type: String,
            },
            numOfPersons: {
              type: Number,
            },
          },
        ],
      },
    ],

and if user want to book a table at 20/8/2021 , 4:00PM we should check available table for this user at this time requested, we should check on tables and return available table the we push the booking information into it..

i tried some query but always return the whole place not just available table..

    const stringDate = new Date(date).toLocaleDateString();
    const placeId = req.body.placeId;

    const availableTable = await Places.findOne({
      _id: placeId,
      "tables[0].bookings": {
        $not: {
          $elemMatch: { $and: [{ Date: stringDate }, { Time: time }] },
        },
      },
    });
    
    availableTable.isBooked = true;
    availableTable.bookings.push({
      Name: name,
      Time: time,
      Date: stringDate,
      numOfPersons: parseInt(personsNumber),
      Note: note,
      User: userId,
    });
   await availableTable.save()
1 Answers

First of all, for simplicity, you should have a separate collection for tables with the restaurant/cafe id in it. That way you can easily do CRUD operations on tables and it would the best approach to handle it.

Related