简体   繁体   中英

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!

I think now you can do it better with the update command on document by using FieldValue.arrayUnion without destroying data that was added meanwhile. Like this:

const admin = require('firebase-admin');
let db = admin.firestore();
const FieldValue = admin.firestore.FieldValue;
let collectionRef = db.collection(collection);
let ref = collectionRef.doc(id);

let setWithOptions = ref.update(arrayFieldName, FieldValue.arrayUnion(value));

As described in https://firebase.googleblog.com/2018/08/better-arrays-in-cloud-firestore.html

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.

Arrays in Firestore don't work like this. According to the documentation :

Although Cloud Firestore can store arrays, it does not support querying array members or updating single array elements.

If you want to change any element in an array, you have to read the array values from the document first, make changes to it in the client, then write the entire array back out.

There are probably other ways to model your data that are better for your use case. That page of documentation linked above has some solutions.

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