如何在JavaScript中获取Firebase实时数据库的指定子节点?
问题1:获取
users下指定子节点User1的值 你的代码逻辑有误:当你获取users节点并遍历其下子节点时,每个child对应的就是User1、User2、User3这些节点本身,child.val()直接返回的是该节点的值(比如User1的val()是"John"),并不是包含User1属性的对象,所以child.val().User1会返回undefined。
两种解决方式:
- 直接定位目标节点路径(最直接高效)
get(child(dbRef, "users/User1")) .then((snapshot) => { if (snapshot.exists()) { console.log(snapshot.val()); // 输出 John } else { console.log("User1 不存在"); } })
- 遍历子节点并匹配key
如果需要遍历users下所有节点,再筛选出User1:
get(child(dbRef, "users/")) .then((snapshot) => { snapshot.forEach((child) => { if (child.key === "User1") { console.log(child.val()); // 输出 John } }) })
问题2:获取用户节点下的Email值
你的代码存在两个核心错误:
- 遍历
Hehefunnyboi2节点的子节点时,每个child对应的是FirstName、LastName、Email、Password这些字段节点,child.val()是字段的具体值(比如FirstName的val()是"Hehe"),不存在Email属性,所以child.val().Email返回undefined。 - 代码中定义了
email变量,但控制台输出的是未定义的name变量,属于变量名错误。
正确解决方式:
方式一:直接获取整个用户对象并提取字段
不需要遍历,直接通过快照获取用户的全部数据,再取出需要的字段:
get(child(dbRef, inputted-username.value)) .then((snapshot) => { if (snapshot.exists()) { const userData = snapshot.val(); console.log(userData.Email); // 输出 Hehefunnyboi2@gmail.com // 如需其他字段,直接通过 userData.FirstName、userData.LastName 访问 } else { console.log("该用户不存在"); } })
方式二:遍历子节点筛选目标字段
如果需要逐个处理用户的每个字段,可以通过判断子节点的key来筛选:
get(child(dbRef, inputted-username.value)) .then((snapshot) => { snapshot.forEach((child) => { if (child.key === "Email") { console.log(child.val()); // 输出邮箱地址 } // 如需处理其他字段,可添加类似判断 // if (child.key === "FirstName") { console.log(child.val()); } }) })
内容的提问来源于stack exchange,提问作者Hehefunnyboi2
相关产品推荐
相关产品推荐

