【问题标题】:How to read, write and query data in Firebase Realtime Database using Firebase SDK v9 (Modular)如何使用 Firebase SDK v9(模块化)在 Firebase 实时数据库中读取、写入和查询数据
【发布时间】:2021-08-06 19:44:18
【问题描述】:

如何从 Firebase 实时数据库执行读写操作和查询数据,v8 中的传统语法是这样的:

const snapshot = await firebase.database().ref("/path").once("value")

考虑样本数据:

{
  "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"
    }
  }
}

另外你将如何使用方法equalTo(), orderByChild(), etc

【问题讨论】:

    标签: javascript firebase firebase-realtime-database


    【解决方案1】:

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

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

    1.初始化 Firebase 应用:

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

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

    import { getDatabase, ref } from "firebase/database"
    
    const db = getDatabase(app) // <-- Pass in the initialized app
    
    //Creating the reference (The path in db you are trying to read/write/update)
    const dbRef = ref("/users")
    

    3.读取操作和监听器:

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

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

    在 v8 中,事件的语法类似于 .on("event_name")。在 v9 中,所有事件都是可以这样使用的方法:

    import { onChildAdded, onChildChanged, onChildRemoved } from "firebase/database"
    
    onChildAdded(query(dbRef), (snapshot) => {
      console.log("child added");
      console.log(snapshot.val()); // Logs newly added child
    });
    
    onChildChanged(query(dbRef), (snapshot) => {
      console.log("child changed")
      console.log(snapshot.val()); // Logs updated value of changed child
    });
     
    onChildRemoved(query(dbRef), (snapshot) => {
      console.log("child removed");
      console.log(snapshot.val()); // Logs value of removed child
    });
    

    4.写入数据:

    // You maybe have figured out the upgrade trend ¯\_(ツ)_/¯
    
    import { set, update } from "firebase/database"
    
    const newUserName = "user1122"
    const userRef = ref(`users/${newUserName}`)
     
    await set(userRef, {name: newUserName, age: 11})
    await update(userRef, {age: 12})
    

    5.使用列表:

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

    import { query, orderByChild, orderByValue, orderByKey, limitToLast } from "firebase/database"
    
    //Example: getting 3 youngest users from the db
    const usersSnapshot = await get(query(dbRef, ...[orderByChild("age"), limitToFirst(3)]))
    

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

    到目前为止,我在使用模块化 SDK 时没有发现任何问题。只要确保你已经导入了所有需要的东西。

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

    import { getApps, initializeApp } from "firebase/app"
    
    if (!getApps().length) initializeApp(firebaseConfig)
    

    【讨论】:

      猜你喜欢
      • 2022-07-20
      • 1970-01-01
      • 2023-03-23
      • 2020-03-10
      • 2019-03-22
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多