如何在不知道Firebase和Firebase-admin中的密钥的情况下让孩子一触即发
我的数据库中有一个队列,如下所示:
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(请参阅下面的答案),但是必须有更好的方法来做到这一点。
当您针对Firebase数据库执行查询时,可能会有多个结果。 所以快照包含了这些结果的列表。 即使只有一个结果,快照也将包含一个结果列表。
Firebase快照有一个内置的方法来迭代其子项:
queueRef.orderByChild('active').equalTo('true').once('value', function(snapshot) { snapshot.forEach(function(child) { console.log(child.key+": "+child.val()); } });
我使用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();