Search code examples
javascriptreact-nativegoogle-cloud-firestorereact-native-firebase

How to add data on nested array in Firestore with react-native


I would like to ask if is it possible to add data in a nested array.The result i want is this enter image description here

But i get this when i add a new rating with the code i use

enter image description here

async function getAll(){
    const userEmail= firebase.firestore().collection('users')
    const snapshot=await userEmail.where('email','==',index.email).get()
    if (snapshot.empty) {
      console.log('No matching documents.');
      return;
    }  
    
    snapshot.forEach(doc => {
      userEmail.doc(doc.id).set({userRatings2:firebase.firestore.FieldValue.arrayUnion({parking:[markerName]})},{merge:true})
      userEmail.doc(doc.id).set({userRatings2:firebase.firestore.FieldValue.arrayUnion({rating:[currentRating]})},{merge:true})

     
      
     console.log(userEmail.doc(doc.id));
    });
  }
  getAll()

Solution

  • Unfortunately in Firebase Firestore you can't even change a simple Array value at a specific index. That means also that you can't save nested array values. You can read more about it on this answer.

    The only way to do it is to download the whole Array make your modifications and save the whole array again to the databse. There is not much context of your app so I can't tell if that is a good solution for you. It depends how much data you have in the array.