Firebase实时数据库读取异常:获取用户价格返回undefined求助
问题描述
尝试展示Firebase实时数据库中用户输入的价格时返回undefined,控制台无报错。使用HTML、JavaScript和CSS开发,相关代码及数据库结构如下:
相关代码
// Initialize Firebase firebase.initializeApp(firebaseConfig); // Initialize variables const database = firebase.database(); const auth = firebase.auth(); firebase.auth().onAuthStateChanged((user) => { if (user) { readData(); } else { window.location.href = "login.html?error"; alert("No active user please sign or sign up."); } }); function readData() { const user = firebase.auth().currentUser; database.ref('/studiopick/studio/users/' + user.uid).get().then(snapshot => { // Tab One Display document.getElementById("studioName").innerText = snapshot.val().studioName; document.getElementById("profile-name").innerText = snapshot.val().studioName; document.getElementById("firstName").innerText = snapshot.val().firstName; document.getElementById("lastName").innerText = snapshot.val().lastName; document.getElementById("email").innerText = snapshot.val().email; document.getElementById("phoneNumber").innerText = snapshot.val().phoneNumber; // Tab Two Display - 此处存在路径问题 document.getElementById("servicePrice").innerText = snapshot.val().numberInput; }).catch(e => { console.log(e) }) } function updatePrice() { const numberInput = document.getElementById("numberInput").value; const user = firebase.auth().currentUser; // 数据写入路径:用户节点下的prices/roomA/serviceOne firebase .database() .ref('/studiopick/studio/users/' + user.uid + "/prices/roomA/serviceOne") .update({ numberInput: numberInput, }); }
数据库结构说明
价格数据存储在用户节点的prices/roomA/serviceOne子路径下,该子节点包含numberInput字段,而非用户根节点直接拥有numberInput字段。
解决方案
问题核心是读取路径与写入路径不匹配:写入时把numberInput放在了prices/roomA/serviceOne子节点,但读取时直接从用户根节点获取numberInput,导致找不到对应字段返回undefined。
1. 修正读取逻辑
修改readData函数中读取价格的代码,深入到正确的子节点路径:
function readData() { const user = firebase.auth().currentUser; database.ref('/studiopick/studio/users/' + user.uid).get().then(snapshot => { // ... 其他信息读取代码保持不变 // 修正价格读取路径 const serviceOneData = snapshot.child('prices/roomA/serviceOne').val(); // 使用可选链操作符避免嵌套undefined报错,同时设置默认值 document.getElementById("servicePrice").innerText = serviceOneData?.numberInput || '暂无价格'; }).catch(e => { console.log(e) }) }
2. 优化数据更新后的体验
在updatePrice函数完成数据写入后,调用readData刷新页面显示,确保用户输入后能立即看到最新价格:
function updatePrice() { const numberInput = document.getElementById("numberInput").value; const user = firebase.auth().currentUser; firebase .database() .ref('/studiopick/studio/users/' + user.uid + "/prices/roomA/serviceOne") .update({ numberInput: numberInput, }) .then(() => { // 数据更新成功后刷新显示 readData(); alert("价格更新成功"); }) .catch(e => { console.log(e) }); }
3. 可选:增加快照存在性检查
为避免用户节点不存在时的报错,可在读取前检查快照是否有效:
function readData() { const user = firebase.auth().currentUser; database.ref('/studiopick/studio/users/' + user.uid).get().then(snapshot => { if (!snapshot.exists()) { console.log("用户数据不存在"); return; } // ... 后续读取代码 }).catch(e => { console.log(e) }) }
内容的提问来源于stack exchange,提问作者user18694296
相关产品推荐
相关产品推荐

