【问题标题】:How do I get child of a snap without knowing the key in firebase and firebase-admin如何在不知道 firebase 和 firebase-admin 中的密钥的情况下快速获得孩子
【发布时间】:2017-06-01 22:51:18
【问题描述】:

我的数据库中有一个如下所示的队列:

server
  queue
    -RANDOM_ID_1234
      active: "true"
      text: "Some text"
    -RANDOM_ID_5678
      active: "false"
      text: "Another text"
    -RANDOM_ID_91011
      active: "false"
      text: "Text that does not matter"

我要查询并获取活动项:

queueRef.orderByChild('active').equalTo('true').once('value', function(snap) {
  if (snap.exists()) {
    console.log(snap.val());
  }
});

console.log 将返回如下内容:

{
  -RANDOM_ID_1234: {
      active: "true"
      text: "Some text"
  }
}

如何在不知道密钥的情况下获取文本?

我使用了 lodash(请参阅下面的答案),但必须有更好的方法来做到这一点。

【问题讨论】:

    标签: node.js firebase firebase-realtime-database firebase-admin


    【解决方案1】:

    当您对 Firebase 数据库执行查询时,可能会有多个结果。所以快照包含这些结果的列表。即使只有一个结果,快照也会包含一个结果列表。

    Firebase 快照具有迭代其子项的内置方法:

    queueRef.orderByChild('active').equalTo('true').once('value', function(snapshot) {
      snapshot.forEach(function(child) {
        console.log(child.key+": "+child.val());
      }
    });
    

    【讨论】:

    • 如果有 getChildAtIndex(0) 或数组表示法 [0] 这样的东西会很棒。
    【解决方案2】:

    我使用 lodash 并得到这样的密钥:

    /* 
     *  I get the keys of the object as array 
     *  and take the first one.
     */
    const key = _.first(_.keys(snap.val())); 
    

    然后像这样从快照中获取文本:

    /* 
     *  then I create a path to the value I want 
     *  using the key.
     */
    const text= snap.child(`${key}/text`).val(); 
    

    【讨论】:

      猜你喜欢
      • 2018-01-18
      • 1970-01-01
      • 2019-07-08
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      • 2017-02-04
      相关资源
      最近更新 更多