0
async function updateBookingSlots(appointmentID) {
  let slotId;
  await firestore
    .collection("bookingSlots")
    .where("appointmentID", "==", appointmentID)
    .get()
    .then((snapshot) => {
      snapshot.forEach((doc) => {
        slotId = doc.id;
      });
    });
  await firestore.collection("bookingSlots").doc(slotId).update({
    appointmentID: "",
    patientID: "",
    requester: "",
  });
}

I'm trying to get the slotId of a booking slot by an appointmentID and then updating the slot. I'm making the calls to same collection twice, is there a way we can combine these two calls in a single call?

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • What do you exactly mean by "combine these two calls in a single call"? I understand that you want to use the `slotId` value in the update call but the Query `firestore.collection("bookingSlots").where("appointmentID", "==", appointmentID)` may return several documents. How do you use `slotId`? Only update the first doc returned by the Query? Or you want to update all the docs returned by the Query? – Renaud Tarnec Mar 24 '23 at 14:23
  • No, Firestore does not have the equivalent of SQL "update where". You have to do one query to find the documents to update, then that many individual document updates. – Doug Stevenson Mar 24 '23 at 14:23
  • @RenaudTarnec Basically the first query will return only one value, as there can be only one slot booked per appointment. – Vinayak Bhat Mar 24 '23 at 14:27

1 Answers1

0

Since you know the first query will return only one document you can do as follows:

async function updateBookingSlots(appointmentID) {

    const snapshot = await firestore
        .collection("bookingSlots")
        .where("appointmentID", "==", appointmentID)
        .get();

    const slotId = snapshot.docs[0].id;  // snapshot.docs[0] = The first and unique DocumentSnapshot in the QuerySnapshot returned by the get() method

    await firestore.collection("bookingSlots").doc(slotId).update({
        appointmentID: "",
        patientID: "",
        requester: "",
    });
    
}

If, on the opposite the first query returns several docs, you should follow the directions detailed in this answer.

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121