Read and write in a same call in Firestore

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?

>Solution :

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.

Leave a Reply