Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

100
Vistas
trying to add an item in the Firestore collection after checking condition that the item does not already exists .if does increasing the quantity else

trying to add an item in the Firestore collection after checking the condition that the item does not already exist.if it does exist increase the quantity of the item else add the new item with quantity 1.

function addToCart(item) {
console.log(item)
let cartItem = db.collection('cart-items').doc(item.id)

cartItem.get()
    .then((doc) => {
        if (doc.exists) {
            cartItem.update({
                quantity: doc.data().quantity + 1
            })
        }
        else {
            cartItem.set({
                image: item.image,
                make: item.make,
                name: item.name,
                rating: item.rating,
                price: item.price,
                quantity: 1
            })
        }
    })

}

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Doing a get-and-set like you're doing here can lead to a race condition if two users update the cart at the same time. You might think that won't happen in you use-case, but I'd still recommend guarding against it by using a transaction.

In this specific case though, it's much simpler and more idiomatic, so always perform a set operation and use the atomic increment operation to increase the quantity:

let cartItem = db.collection('cart-items').doc(item.id)
cartItem.set({
    image: item.image,
    make: item.make,
    name: item.name,
    rating: item.rating,
    price: item.price,
    quantity: firebase.firestore.FieldValue.increment(1)
})

It may feel wasteful to send the other field values multiple times, but you won't be charged more for the operation by Firestore here, and the code simplification is significant.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda