![](/img/trans.png)
[英]How to update data in Firebase realtime database using Firebase 9 (modular sdk)
[英]How to read, write and query data in Firebase Realtime Database using Firebase SDK v9 (Modular)
如何从 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
方法?
免责声明: v9 模块化 SDK 是测试版。 语法可能(或可能不会)改变,但我会尽快更新答案。 可以在 此处找到此升级的好处。
模块化的SDK不能通过CDN使用,暂时需要使用npm或者yarn。 我已经在 Vue 网络应用程序中对此进行了测试。
1.初始化Firebase App:
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';
'endAt' | 'endBefore' | 'startAt' | 'startAfter' | 'limitToFirst' | 'limitToLast' | 'orderByChild' | 'orderByKey' | 'orderByPriority' | 'orderByValue' | 'equalTo';
. 您可以将它们作为单独的参数传递,而不是像我使用的那样使用扩展运算符。
到目前为止,我没有发现使用模块化 SDK 的问题。 只要确保你已经导入了所有需要的东西。
PS:以防万一,如果您在开发时使用 Vue、React 或任何带有热重载的框架,您可能会遇到“Firebase App named '[DEFAULT]' already exists (app/duplicate-app)”错误。 检查firebase.apps.length
是否为 0 有帮助,这在模块化 SDK 中以这种方式完成:
import { getApps, initializeApp } from "firebase/app"
if (!getApps().length) initializeApp(firebaseConfig)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.