'How to add a new value to a Firestore field in a document in addition to the previous value?

I want to create a function that checks if a collection in Firestore exists and if it exist I want it to add the value given by the user to the value stored in the document inside the collection

My approach:

  items.forEach(item=>
  
      User &&  db.collection("users").doc(Uid).collection("basket").where( "id" , "==" , item.id)
      .get().then(function(querySnapshot) {
        if (querySnapshot.empty) {
          
                 // DO SOMETHING

        }
         else {
         
          db.collection("users").doc(Uid).collection("basket").where("id" == item.id)
          .get().then((docs) => {
        
            docs.forEach((doc) =>{ doc.ref.set({
              quantity : firebase.firestore.FieldValue.increment(item.quantity)
            })}).then(setLocked(true))
          
           
        })
               
        }
    })
    )

however it shows the following error :

Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'ut')

I doubled check the code and it turns out that the error comes from the beginning of the query the else statement however there is nothing wrong with it



Solution 1:[1]

As Stf_F commented, you can either pass merge: true to the set call:

docs.forEach((doc) =>{ 
  doc.ref.set({
    quantity : firebase.firestore.FieldValue.increment(item.quantity)
  }, { merge: true }) // ?
})

or you can use update:

docs.forEach((doc) =>{ 
  doc.ref.update({ // ?
    quantity : firebase.firestore.FieldValue.increment(item.quantity)
  })
})

The .then(setLocked(true)) makes no sense, since forEach doesn't return a promise.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frank van Puffelen