如何使用 Firebase SDK v9(模块化)读取、写入和查询 Firebase 实时数据库中的数据

Dha*_*raj 8 javascript firebase firebase-realtime-database

如何执行读写操作以及从 Firebase 实时数据库查询数据,v8 中的传统语法如下:

const snapshot = await firebase.database().ref("/path").once("value")
Run Code Online (Sandbox Code Playgroud)

考虑样本数据:

{
  "users" : {
    "user1" : {
      "age" : 34,
      "name" : "user1"
    },
    "user2" : {
      "age" : 23,
      "name" : "user2"
    },
    "user345" : {
      "age" : 19,
      "name" : "user345"
    },
    "user4" : {
      "age" : 15,
      "name" : "user4"
    },
    "user56" : {
      "age" : 45,
      "name" : "user56"
    },
    "user9435" : {
      "age" : 8,
      "name" : "user9435"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

另外你会如何使用这些方法equalTo(), orderByChild(), etc

Dha*_*raj 21

免责声明: v9 模块化 SDK 是测试版。语法可能(或可能不会)改变,但我会尝试尽快更新答案。可以在此处找到此升级的好处。

\n

模块化SDK无法通过CDN使用,暂时需要使用npm或yarn。我已经在 Vue 网络应用程序中对此进行了测试。

\n

1. 初始化 Firebase 应用程序:

\n
import { initializeApp } from "firebase/app";\n\nconst firebaseConfig = { \n  apiKey: "<api-key>",\n  authDomain: "<project-id>.firebaseapp.com",\n  databaseURL: "https://<project-id>.firebaseio.com",\n  projectId: "<project-id>",\n  storageBucket: "<project-id>.appspot.com",\n  messagingSenderId: "0000000000",\n  appId: "<app-id>",\n}\n\nconst app = initializeApp(firebaseConfig)\n
Run Code Online (Sandbox Code Playgroud)\n

2. 创建数据库实例和引用:

\n
import { getDatabase, ref } from "firebase/database"\n\nconst db = getDatabase(app) // <-- Pass in the initialized app\n\n//Creating the reference (The path in db you are trying to read/write/update)\nconst dbRef = ref("/users")\n
Run Code Online (Sandbox Code Playgroud)\n

3. 读操作和监听器:

\n

您需要使用get()方法来检索接受查询作为参数的数据。如果您只是读取数据而不进行任何排序或过滤,只需将上面创建的引用传递到query(). (注意:在这种情况下直接在 get() 中传递引用是有效的)

\n
import { get, query, onValue } from "firebase/database"\n\nconst usersSnapshot = await get(query(dbRef)) //This should get the whole users node from db.\n\n//To add a listener you can use the onValue() method like,\nonValue(query(dbRef), snapshot => {\n  console.log(snapshot.val())\n})\n\n//\n
Run Code Online (Sandbox Code Playgroud)\n

在 v8 中,事件的语法如下所示.on("event_name")。在 v9 中,所有事件都是一个方法,可以这样使用:

\n
import { onChildAdded, onChildChanged, onChildRemoved } from "firebase/database"\n\nonChildAdded(query(dbRef), (snapshot) => {\n  console.log("child added");\n  console.log(snapshot.val()); // Logs newly added child\n});\n\nonChildChanged(query(dbRef), (snapshot) => {\n  console.log("child changed")\n  console.log(snapshot.val()); // Logs updated value of changed child\n});\n \nonChildRemoved(query(dbRef), (snapshot) => {\n  console.log("child removed");\n  console.log(snapshot.val()); // Logs value of removed child\n});\n
Run Code Online (Sandbox Code Playgroud)\n

4、写入数据:

\n
// You maybe have figured out the upgrade trend \xc2\xaf\\_(\xe3\x83\x84)_/\xc2\xaf\n\nimport { set, update } from "firebase/database"\n\nconst newUserName = "user1122"\nconst userRef = ref(`users/${newUserName}`)\n \nawait set(userRef, {name: newUserName, age: 11})\nawait update(userRef, {age: 12})\n
Run Code Online (Sandbox Code Playgroud)\n

5. 使用列表:

\n

这是最好的部分,现在感觉有点类似于在 MongoDB 聚合中添加阶段。

\n
import { query, orderByChild, orderByValue, orderByKey, limitToLast } from "firebase/database"\n\n//Example: getting 3 youngest users from the db\nconst usersSnapshot = await get(query(dbRef, ...[orderByChild("age"), limitToFirst(3)]))\n
Run Code Online (Sandbox Code Playgroud)\n

第一个参数是query()数据库引用,以下所有参数都是 QueryConstraints,可以是以下方法之一:\'endAt\' | \'endBefore\' | \'startAt\' | \'startAfter\' | \'limitToFirst\' | \'limitToLast\' | \'orderByChild\' | \'orderByKey\' | \'orderByPriority\' | \'orderByValue\' | \'equalTo\';。您可以将它们作为单独的参数传递,而不是像我使用的那样使用扩展运算符。

\n

到目前为止,我在使用模块化 SDK 时没有发现任何问题。只需确保您已导入所需的所有内容即可。

\n

PS:以防万一,如果您在开发时使用 Vue、React 或任何具有热重载功能的框架,您可能会遇到“名为 \'[DEFAULT]\' 的 Firebase App 已存在 (app/duplicate-app)”错误。检查是否firebase.apps.length为 0 有帮助,在模块化 SDK 中是这样完成的:

\n
import { getApps, initializeApp } from "firebase/app"\n\nif (!getApps().length) initializeApp(firebaseConfig)\n
Run Code Online (Sandbox Code Playgroud)\n