【问题标题】:Firestore - how to add/subtract from a map of valuesFirestore - 如何从值映射中添加/减去
【发布时间】:2018-10-20 06:09:25
【问题描述】:

我正在遵循 Firestore 存储数组的说明: https://firebase.google.com/docs/firestore/solutions/arrays

现在我想做的是推送到这张地图。例如现在我有:

Contacts
   contact1: true

但我想添加或删除联系人,例如:

Contacts
   contact1: true
   contact2: true

我已尝试获取联系人地图并使用推送方法,但我认为这不会起作用,因为它不是传统数组。例如:

this.afs
  .doc(`groups/${group.id}`)
  .ref.get()
  .then(doc => {
    let contacts: Array<any> = doc.data().contacts;

    contacts.push({ // error here as push is not a function
      [contactId]: true
    });

    console.log(contacts);
  });

有没有更简单的方法来做到这一点 - 我错过了什么?

【问题讨论】:

    标签: angular firebase google-cloud-firestore angularfire2


    【解决方案1】:

    只需推入地图

    如下使用update()

    const db = firebase.firestore();
    const collection = db.collection('collectionId');
    
    collection.doc(`groups/${group.id}`).update({
    
          "Contacts.contact3":true
    
        }).then(function(){
    
           console.log("Successfully updated!");
    
    });
    

    【讨论】:

    • 反响很好。我还要补充一点,由于“contact3”通常是一个变量 ID,因此您可以使用计算属性名称 (ES6)。例如:[`contacts.${contactID}`]: true.
    • 这是否仍然/与 firestore 模拟器一起工作?当我尝试这个时,我只是在文档中得到一个字段 contacts.idsagjoisagjoisjfoiwajfi: true 而不是 Contacts :{asfsafasfgasgf: true}
    【解决方案2】:

    首先,您不能对对象使用 push 方法,因为地图不是数组。

    您可以简单地使用 .[] 运算符在 JS 中访问/添加/更新地图的值。

    对于存储在 Firestore 中的对象(如数组和对象),您不能真正直接将值“推送”给它们。您首先需要获取包含它们的文档,然后在本地更新它们的值。

    完成后,将值更新到 Firestore。

    为简化流程,如果您使用 Cloud Functions,可以使用 Firestore SDK 或 Admin SDK 提供的 runTransaction() 方法。

    下面是为您完成工作的代码。

    const docRef = this.afs.doc(`groups/${groupId}`);
    
    db.runTransaction((t) => { // db is the firestore instance
      return t.get(docRef).then((doc) => { // getting the document from Firestore
        // {} is a fallback for the case if the "obj" is not present in the firestore
        const obj = doc.get("contacts") ? doc.get("contacts") : {};
        obj[contactId] = true; // updating the value here locally
    
        t.set(docRef, { contacts: obj }, { // updating the value to Firestore.
          merge: true,
        });
    
        return;
      }).then((result) => {
        console.log('map updated', result);
        return;
      }).catch((error) => handleError(error));
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2019-12-29
      • 2021-03-19
      • 1970-01-01
      • 2011-12-04
      • 2021-07-02
      相关资源
      最近更新 更多