Firebase Atmonic 添加和删除条目

Firebase Atmonic Add and delete entry

我的 firebase 中有以下数据结构

-ActionSheet
    -PendingApproval 
        -SomeKey1
            -someData
            -someData
            -someData
        -SomeKey2
            -someData
            -someData
            -someData
    -Approved
        -SomeKey3
            -someData
            -someData
            -someData

当屏幕出现时,用户会看到所有处于 pendingApproval 中的项目。 当用户在其中一个条目上单击批准时,我想将数据从 "PendingApproval" 移动到 "Approved" 节点。

假设用户点击了 SomeKey1 的批准,目前,我正在按照以下方式进行操作

1. Duplicate the data to Approved node 

2. Upon success, delete the entry SomeKey1 from PendingApproval 

不过也有小概率第一步成功第二步失败。在这种情况下,我的数据库中会有两个 SomeKey1

我想知道是否有一种方法可以自动执行此操作,从而保证操作同时成功或失败。

我刚读过 Firebase Atmoic,他们只提到原子更新反对 "set + remove"。

下面是我的代码

// save data to firebase
saveoFirebase_approved(myData: Object, key: string) {
    let savePath = '/ActionSheet/Approved/' + key;
    return this.af.database.object(savePath).set(myData);
}

// remove pending approval from firebase
removePendingFromFirebase(myData: Object) {
    let savePath = '/ActionSheet/PendingApproval/' + key;
    return this.af.database.object(savePath).remove();
}


this.databaseService.saveoFirebase_approved(data, key)
  .then(result => {

    // delete pending from firebase
    this.databaseService.removePendingFromFirebase(data)
      .then(result => {
        // both action completed
      })
      .catch(error => {
        // something went wrong deleting item from firebase
      })
  })
  .catch(error => {
    // something went wrong saving to firebase
  })
 }

注意:我正在使用 Angular 2 和 AngularFire

你在找我相信的所谓的交易。

https://firebase.google.com/docs/database/web/read-and-write#save_data_as_transactions

您可以通过将 null 设置为该位置来删除 multi-location 更新中的数据。所以你的操作变成:

var updates = {
  'PendingApproval/SomeKey1': null,
  'Approved/SomeKey1': {
    SomeDate: 'Value'
  }
};
ref.child("ActionSheet").update(updates);

您甚至可以在您的安全规则中验证数据只能写入 Approved 如果它以前是待处理的并且现在不再是待处理的:

"Approved": {
  "$key": {
    ".write": "data.parent().parent().child('PendingApprocal').child($key).exists()
        && !newData.parent().parent().child('PendingApprocal').child($key).exists()"