0

I am trying to update the object which is in array and that array in object. I am using mongoose I have 2 schemas SlotTracker and Slot. I am adding slot in array. as following. this is my database.


[{
  "_id": {
    "$oid": "60a39e210976153090842b46"
  },
  "bookings": [
    {
      "_id": {
        "$oid": "60b8ac254006ed40604eac86"
      },
      "aDate": {
        "$date": "2021-06-12T00:00:00.197Z"
      },
      "aShift": "morning",
      "slotsAvailable": 3,
      "slotsBooked": 0
    },
    {
      "_id": {
        "$oid": "60b8ac384006ed40604eac9d"
      },
      "aDate": {
        "$date": "2021-06-14T00:00:00.197Z"
      },
      "aShift": "morning",
      "slotsAvailable": 3,
      "slotsBooked": 0
    }
  ],
  "courtID": 2,
  "__v": 0
},
{
  "_id": {
    "$oid": "60b7a9199f7c244f3c9053c4"
  },
  "bookings": [
    {
      "_id": {
        "$oid": "60b8ac604006ed40604eacb5"
      },
      "aDate": {
        "$date": "2021-06-12T00:00:00.197Z"
      },
      "aShift": "morning",
      "slotsAvailable": 6,
      "slotsBooked": 0
    },
    {
      "_id": {
        "$oid": "60b8ac6d4006ed40604eaccd"
      },
      "aDate": {
        "$date": "2021-06-13T00:00:00.197Z"
      },
      "aShift": "morning",
      "slotsAvailable": 6,
      "slotsBooked": 0
    }
  ],
  "courtID": 3,
  "__v": 0
}]

I am tring to change values of slotsBooked and slotsAvailale if they exist in booking array of that requested court. if it is not there in array of requested court then add new slot int array of that court.

schemas

  • SlotTracker :
Schema({
courtId: {
        type: Number
    },
    bookings: {
        type: Array
    }
});
  • Slot
Schema({
    aDate: {
        type: Date
    },
    aShift: {
        type: String
    },
    slotsAvailable: {
        type: Number
    },
    slotsBooked: {
        type: Number
    }
});

I want to change the slotAvailable and slotBooked if and only if that aDate and aShift matches with provided aDate and aSlot

1 Answer 1

0

You can use this aggregation framework trick: https://stackoverflow.com/a/46323107/606351

Basically filter the array and then override what properties you want changed or added.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried but I was unable to write query for that. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.