Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
Prevent Map Update if Key Exists

I'm trying to create a backend in firestore to manage availability. I have an employeeAvailability collection with documents for each employee that each contain a map where the keys are start times of the appointment booked for that employeee. The data is used to generate timeslots on the client side that a user can select to book (an appointment means the timeslot is unavailable).

employee12345 {
    appointments = { "10:00 AM" : true,
                     "11:00 AM" : true,
                     "12:00 PM" : true,
                     "1:00 PM" : true, 
                     "2:00 PM" : true
    }
}

I wanted to create a firestore rule that prevents users from double booking an appointment. When the user tries to book a timeslot for 1:00 PM, in the above example, I'd need to do the following update.

db.collection("employeeAvailability").document("employee12345").updateDate([
     "appointments.1:00 PM": true
]) { err in
    if let err = err {
        print("Error updating document: \(err)")
    } else {
        print("Document successfully updated")
    }
}

I'd like this transaction to be rejected and the firebase err to say something along the lines of "This appointment slot is already booked".

Obviously, there are client side rules preventing people from choosing booked timeslots, but it's possible I could have users simultaneously trying to book the same open spot and I'd like the database to handle these race conditions by accepting the first write and rejecting the second.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I'd like the database to handle these race conditions by accepting the first write and rejecting the second.

You should then use a transaction, along the following lines:

  const db = firebase.firestore();

  const employeeDocRef = db
    .collection('employeeAvailability')
    .doc('employee12345');

  const timeSlot = '1:00 PM';

  db.runTransaction((transaction) => {
    return transaction.get(employeeDocRef).then((employeeDoc) => {
      const appointments = employeeDoc.get('appointments');

      if (appointments.hasOwnProperty(timeSlot)) {
        throw 'Slot already taken';
      }

      appointments[timeSlot] = true;
      transaction.update(employeeDocRef, { appointments });
    });
  })
    .then(() => {
      console.log('Transaction successfully committed!');
    })
    .catch((error) => {
      console.log('Transaction failed: ', error);
    });
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda