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

103
Visualizações
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 Respostas
Responde à pergunta

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 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