代码之家  ›  专栏  ›  技术社区  ›  rhysclay

Firestore-如何从值映射中添加/减去

  •  9
  • rhysclay  · 技术社区  · 6 年前

    我遵循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);
      });
    

    有没有更简单的方法来做到这一点-我是否遗漏了什么?

    2 回复  |  直到 6 年前
        1
  •  26
  •   voomin kim    6 年前

    只需推入地图

    使用 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!");
    
    });
    
        2
  •  9
  •   Utkarsh Bhatt    6 年前

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

    您只需使用 . [] 运算符访问/添加/更新JS中映射的值。

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

    完成后,将值更新到Firestore。

    要简化此过程,可以使用 runTransaction() 方法由Firestore SDK或Admin SDK提供(如果您使用的是云函数)。

    这是将为您完成工作的代码。

    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));
    });