简体   繁体   中英

Conditionally updating a Firestore document

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.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM