Home > Software engineering >  Conditionally updating a Firestore document
Conditionally updating a Firestore document

Time:11-17

I am trying to conditionally update a document in my react native project and I have not fully understood how that works in react native or if it is impossible. I would really appreciate if someone can explain me the logic.

below is my code i have been playing around with

useEffect( () => {

firebase.firestore().collection('orders').doc(firebase.auth().currentUser.uid)
.collection('pending').where('price', '==', 55000).onSnapshot((snapshot) => {
  let items = snapshot.docs.map(doc => {
      const data = doc.data();
      const id = doc.id;
      
      setItemId(id)
      setBrand(data.brand)
      setColor(data.color)
      setDescription(data.description)
      setDownloadUrl(data.downloadUrl)

      setPrice(25000)

      return{id, ...data }
  })
})

 
 firebase.firestore().collection('orders').doc(firebase.auth()
.currentUser.uid)
 .collection('pending').doc(itemId).set({
price,
brand,
color,
description,
downloadUrl,
})

So what i did in this code was to run through all the data in the document and look for any that has it's price == 55000 then re-write it's data changing only the old price to the new one (please pardon me if it is not clear). But what this code does is that it deletes the old data and create a new document with empty data.

CodePudding user response:

You could just simply iterate the result from snapshot and update the field from the document reference. See sample code below:

firebase.firestore().collection('orders').doc(firebase.auth().currentUser.uid)
  .collection('pending').where('price', '==', 55000)
  .onSnapshot((snapshot) => {
    snapshot.forEach((doc) => {
      doc.ref.update({'price': 25000})
    });
  });

For more information you may check out this documentations:

  • Related