【问题标题】:Update object child without id in Firebase function在 Firebase 函数中更新没有 id 的对象子对象
【发布时间】:2018-10-10 16:24:37
【问题描述】:

希望你能帮助我。

在 firebase 数据库函数的触发器中,我正在尝试更新 不知道 id 的孩子的对象。

所以,我想通过只知道类别元素而不知道产品类别来更新类别元素。

请帮忙...

【问题讨论】:

    标签: firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    您可以先检索类别数据。假设您知道第一个键(LNBxRLsPR0OY8-_Cnm)并且您只有一个类别项目(如果多个类别将用另一个代码快照解释)

    firebase.database().ref('product/' + key + '/categoria').once('value', snapshot=>{
      if (snapshot.exists()) var categoriaKey = Object.keys(snapshot.val()[0])
      firebase.database().ref('product/' + key + '/' + categoriaKey).set(newCategoriaObject)
    })
    

    编辑:

    productList={}
    firebase.database().ref('product').once('value', snap=>{
       snap.forEach(p=>{
          productList[p.key]=p.val().name; 
       })
    }) 
    

    上面的产品列表对象数组。场景:您需要向用户显示产品名称列表。用户选择产品后,您可以通过以下功能检索密钥。

    function findKey(productList, selectedProductName) { 
         for (let key in productList)
            if (productList[key] === selectedProductName) return key;
    }
    
    key = findKey(productList, selectedProductName);
    

    因此,使用上述简单代码,您将获得用户选择的产品密钥。如果你没有其他场景:)

    【讨论】:

    • 如果我不知道产品密钥怎么办?
    • 然后您将以与上面显示的代码相同的方式检索产品密钥。这时候你会有一堆钥匙。您可以使用 forEach 方法循环所有产品密钥。 (所以首先你需要知道产品密钥)
    • 好的,我怎样才能在 firebase 函数中获取密钥?
    • 您需要每个产品 ID 或描述才能选择要更新的产品。所以。你将有两个步骤。在第一步。您将检索产品密钥并从其 id 中选择产品,然后您将检索该产品的类别。我会更新上面的代码。
    • 完全有效!!谢谢!
    猜你喜欢
    • 2016-07-19
    • 2019-08-29
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 2020-02-05
    相关资源
    最近更新 更多