如何在Firebase实时数据库中匹配子节点的子节点与本地存储数据
Firebase实时数据库匹配异常问题
场景说明
我开发了一个QR码扫描工具,扫描后会匹配Firebase实时数据库中的数据,匹配成功则跳转至下一页,并将QR码对应的machine_id存入localStorage。但跳转后页面的数据匹配代码,在两种不同的数据库结构下表现不一致:
情况一:数据库层级为All_machines -> Generator -> [machine_id](匹配失败)
数据库结构:All_machines节点下有Generator子节点,Generator节点内以machine_id作为键存储对应的数据条目。
使用的代码:
var db= app.database() let machine_id = localStorage.getItem('machineid') // 控制台输出正确的machine_id:8c96aa286f24 db.ref('/All_machines/Generator/').orderByKey().equalTo(machine_id).once("value", snapshot => { if (snapshot.exists()){ const userData = snapshot.val(); var snapshot= snapshot.child(machine_id).val(); console.log(userData); // 控制台无任何输出,也没有报错信息 } })
执行后控制台没有输出,也不报错,无法获取数据。
情况二:数据库层级为All_machines -> [machine_id](匹配成功)
调整数据库结构:All_machines节点直接以machine_id作为键存储对应的数据条目。
修改后的代码:
var db= app.database() let machine_id = localStorage.getItem('machineid') db.ref('/All_machines').orderByKey().equalTo(machine_id).once("value", snapshot => { if (snapshot.exists()){ const userData = snapshot.val(); var snapshot= snapshot.child(machine_id).val(); console.log(userData); } })
执行后控制台能正常输出对应的数据,匹配成功。
疑问
为什么当machine_id位于Generator节点下时,代码无法成功匹配并获取数据?
内容的提问来源于stack exchange,提问作者MOHAMMAD ZEESHAN
相关产品推荐
相关产品推荐

