我的Firebase实时数据库的结构如下:
-- Stock
-- StoreId
-- DepartmentId_1
-- ProductId_1
-- name: "productName"
-- price: 1.0
-- DepartmentId_2
-- ProductId_X
-- name: "productNameX"
-- price: 1.0
我想阅读DepartmentId
,以在RecyclerView
中显示它们。但是Android Firebase侦听器会检索StoreId
中包含的所有数据。
我知道我可以使用for循环并获取密钥,但这不是重点。问题是下载的数据量很大,这可能会使我在Firebase中的配额爆炸。
因此,我决定使用Cloud Functions在其他节点中编写密钥,如下所示:
-- Departments
-- StoreId
-- DepartmentId_1: true
-- DepartmentId_2: true
-- DepartmentId_3: true
-- DepartmentId_4: true
.
.
.
我认为Cloud Functions仅会在特定节点上触发,但是事实证明,如果我更改price
字段,则会触发我的Cloud Function
。
所以我的问题是:仅在添加或删除departmentId
时如何触发我的Cloud Function?
下面是我的第一步,那么如何遍历departmentId
,并在 Departments 节点中编写它们?
exports.createStoreDepartments = functions.database
.ref('Stock/{storeId}')
.onWrite((change,context) => {
console.log('DATA CHANGED');
return true;
});
感谢您的帮助!
答案 0 :(得分:2)
仅在添加或删除
departmentId
时如何触发我的Cloud Function?
有两种方法可以做到这一点:
带有两个单独的触发器。
exports.createStoreDepartments = functions.database
.ref('Stock/{storeId}/{departmentId}')
.onCreate((snapshot, context) => {
...
和
exports.createStoreDepartments = functions.database
.ref('Stock/{storeId}/{departmentId}')
.onDelete((snapshot, context) => {
...
具有单个onWrite
触发器。
exports.createStoreDepartments = functions.database
.ref('Stock/{storeId}/{departmentId}')
.onWrite((change,context) => {
if (!change.before.exists()) {
// TODO: this department was just created
}
if (!change.after.exists()) {
// TODO: this department was just deleted
}});