Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push an array value in Firebase Firestore

I am trying to push an array element but am destroying all the content there and replacing with the pushed data:

db .collection('households')
  .doc(householdId)
  .set( { users: [uid], }, { merge: true }, )
  .then(() => { resolve(); })
  .catch(() => reject());

I thought the merge true doesn't destroy the data that is already there? Struggling a little with the firestore api docs.

This is the structure of my data:

households
  2435djgnfk 
    users [ 
      0: user1 
      1: user2 
    ]

Thank you!

like image 348
Le Moi Avatar asked Apr 19 '18 08:04

Le Moi


People also ask

How do I pass an array to firestore?

When passing an array using either of the above methods, Firestore will only add new array elements to that do not already exist in the Firestore array. let myArray = ["2", "3", "5", "7"]; docRef. update({ test: firebase.

How do you update an array of objects in firestore?

// Atomically remove a region from the "regions" array field. # Atomically add a new region to the 'regions' array field. # // Atomically remove a region from the 'regions' array field. # Atomically add a new region to the 'regions' array field.

Is there any way to update a specific index from the array in firestore?

Is there any way to update a specific index from the array in Firestore? No, there is not! This is not possible because if you want to perform an update, you need to know the index of that particular element. When talking about Cloud Firestore arrays, the things are different that you might think.


1 Answers

You should use Firestore Transaction for this.

const householdRef = db.collection('households').doc(householdId);

const newUid = '1234'; // whatever the uid is...

return db.runTransaction((t) => {
  return t.get(householdRef).then((doc) => {
    // doc doesn't exist; can't update
    if (!doc.exists) return;
    // update the users array after getting it from Firestore.
    const newUserArray = doc.get('users').push(newUid);
    t.set(householdRef, { users: newUserArray }, { merge: true });
  });
}).catch(console.log);

Updating an array or a stored object without getting it first will always destroy the older values inside that array/object in firestore.

This is because they are fields and not actual document themselves. So, you have to first get the document and then update the value after that.

like image 118
Utkarsh Bhatt Avatar answered Oct 01 '22 08:10

Utkarsh Bhatt