Firebase on('child_added' 正在添加更多不需要的子项 / .once 仅返回数组中的最后一个子项



在节点脚本上工作,以便在提供json文件中列出的网站时自动调用Google的pagespeed api。

{
"1" : "https://bitbucket.org",
"2" : "https://www.catswhocode.com/blog/"
}

目的是将 api 调用的结果添加到 firebase json 数据库,以及一个顶级网址节点,用于存储输入的站点统计信息的 firebase 密钥。这是我需要的示例火力基础数据结构。

sites
-KrehhWxld7XlKCuFSHRY
stats { ... }
url: "https://bitbucket.org"
-KrehhXAWlYdjAOA9sd95
stats { ... }
url: "https://stackoverflow.com"
urls :
393957be871e209a76e0dc5df1f526ec : -KrehhWxld7XlKCuFSHRY
7f4c919540be6ec81cd37d9e61da6c37 : -KrehhXAWlYdjAOA9sd95

在承诺中,我正在为Firebase json数据库中的节点添加引用。

Promise.all(allRes).then( function( values ) {
var ref = db.ref();
var sitesRef = ref.child("sites");
var urlsRef = ref.child("urls");
var psiresults = {};
SitesArray.map(function (sites, index) {
psiresults[sites] = values[index]
desktopStats = values[index].desktopStats;
mobileStats = values[index].mobileStats;
sitesRef.push({
url: sites,
stats: metricsResponse
});
sitesRef.once('child_added', function(snapshot) {
console.log(snapshot.key) //returns the last key only
});
});

使用once('child_added', ...时,它仅添加到最后一项的 url 顶级节点。但是,如果on('child_added', ...添加相同数据的多个副本和其他子项。不确定每次将子项添加到站点节点时如何将确切的子键添加到urls顶级节点。

如果要一次性处理所有URL,请将once('value'snapshot.forEach()一起使用:

sitesRef.once('value', function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key);
});
});

最后,我不得不使用..

sitesRef.on('value', function(snapshot) {
... 
});

这将返回所有子项,然后我能够根据我的 SitesArray 值过滤结果。我真的不觉得这是一个合适的解决方案,但是,我能够让它工作。

最新更新