如何将 Firebase 数据库的值分配给 JavaScript 变量?

huangapple go评论62阅读模式
英文:

How do a assign a firebase database value to a variable in javascript?

问题

是否有一种方法可以将变量分配给实时数据库的值?如果可以的话,我可以得到一些帮助吗?

英文:

I don't have any code because this is just a theoretical idea. But would there be a way to assign a variable to a realtime database value? If so, could I get some help?

答案1

得分: 1

让我们假设您有以下数据库结构:

user: 123
    name: user 

假设您想要获取 name 的值一次并将其分配为变量,然后在控制台中记录它。

由于您想要使用 Firebase 的 get(),您将使用以下代码:

import { getDatabase, ref, child, get } from "firebase/database";

const dbRef = ref(getDatabase());
get(child(dbRef, `123`))
    .then((snapshot) => {
        snapshot.forEach((child) => {
            let name = child.val(); // user
            console.log(hello);
            let key = child.key; // name
            console.log(key);
        });
    })
    .catch((error) => {
        console.error(error);
    });

在上述代码中,我访问了 123 并使用 forEach 遍历快照(在本例中只有一个 - name),我将其称为 childchild.val() 将打印 user(即文档的值),而 child.key 将打印 name(即文档的键),我可以轻松将它们分配给变量并在任何地方使用,比如 console.log()

我已经个人测试了这段代码,但它应该按预期工作。

英文:

Let's say you have the following database structure:

user: 123
    name: user

And let's say you want to get the value of name once and assign it as a variable and log it in the console.

And since you want to use Firebase's get(), you'll use:

import { getDatabase, ref, child, get } from "firebase/database";

const dbRef = ref(getDatabase());
get(child(dbRef, `123`))
    .then((snapshot) => {
        snapshot.forEach((child) => {
            let name = child.val(); // user
            console.log(hello);
            let key = child.key; // name
            console.log(key);
        });
    })
    .catch((error) => {
        console.error(error);
    });

In the above code, I access 123 and forEach snapshot (which in this case only one - name), I'll call it child. And child.val() will print user (aka the value of the document) and child.key will print name (aka the key of the document) and I can easily assign them to variables and use them anywhere like console.log().

I've tested the code personally, but it should work as expected.

huangapple
  • 本文由 发表于 2023年6月26日 10:18:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76553185.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定