How to add values to Firebase Firestore without overwriting?

前端 未结 5 1728
孤独总比滥情好
孤独总比滥情好 2020-12-16 17:56

I have two Activities, I am adding data to Firestore from these two activities individually. But, whenever I add second activity data to Firestore, it is overwriting the fir

5条回答
  •  一生所求
    2020-12-16 18:21

    Try this for a direct update

    db.collection('cities').doc('restaurants').update({ rating:"3.2" });

    Only the field rating is going to change, the rest of the fields will remain the same.

    Lets say you have 3 fields, and want to change only 2 of them, you can also do this in a different way

    // You get the document 'restaurants' and then do the below
    db.collection('cities').doc('restaurants').get().then((doc) => {
    
        // Get the rating field string, parse it to a float, remove 0.4 from it and
        // set it to a tmp variable
        var tmpRating = parseFloat(doc.data()['rating']) - 0.4;
    
        // Get the array of strings field 'menu' and set it to a tmp variable
        var tmpMenu = doc.data()['menu'];
    
        // Push 'spaghetti' string to the tmp array of strings( Can also put an
        // adapting string variable instead of a specific string like 'spaghetti'
        tmpMenu.push('spaghetti');
    
        // Update only the specific fields 'rating' and 'menu' and keep the rest unchanged.
        db.collection('cities').doc(doc.id).update({
            rating: toString(tmpRating), // Don't forget to separate them by commas
            menu: tmpMenu
        });
    });
    

提交回复
热议问题