Firestore Add value to array field

后端 未结 2 379
说谎
说谎 2020-12-09 08:57

Im trying to use Firebase cloud functions to add the id of a chatroom to the users document in an array field. I cant seem to figure out the way to write to an array field t

相关标签:
2条回答
  • 2020-12-09 09:14

    Firestore currently does not allow you to update the individual fields of an array. You can, however, replace the entire contents of an array as such:

    admin.firestore().doc(`users/${userA}/chats`).update('array', [...]);
    

    Note that this might override some writes from another client. You can use transactions to lock on the document before you perform the update.

    admin.firestore().runTransaction(transaction => {
      return transaction.get(docRef).then(snapshot => {
        const largerArray = snapshot.get('array');
        largerArray.push('newfield');
        transaction.update(docRef, 'array', largerArray);
      });
    });
    
    0 讨论(0)
  • 2020-12-09 09:39

    From the docs, they added a new operation to append or remove elements from arrays. Read more here: https://firebase.google.com/docs/firestore/manage-data/add-data

    Example:

    var admin = require('firebase-admin');
    // ...
    var washingtonRef = db.collection('cities').doc('DC');
    
    // Atomically add a new region to the "regions" array field.
    var arrUnion = washingtonRef.update({
      regions: admin.firestore.FieldValue.arrayUnion('greater_virginia')
    });
    // Atomically remove a region from the "regions" array field.
    var arrRm = washingtonRef.update({
      regions: admin.firestore.FieldValue.arrayRemove('east_coast')
    });
    
    0 讨论(0)
提交回复
热议问题