如何将列表推送到 Firebase 实时数据库

How to push a list to Firebase Realtime Database

我正在 Ionic 3 上开发移动应用程序。 我在 firebase 数据库上有一个通知 object。我正在以这种方式推送一条记录的数据:

fireNots = firebase.database().ref('/notifications');
addNotification(notReq: INotReq){
   this.fireNots.child(notReq.RecipientUId).push({
      Title: notReq.Title,
      Body: notReq.Body
      }).then(() => {
        resolve({ success: true });
      })     
}

这是 INotReq:

export interface INotReq{
    RecipientUId: string,
    Title: string,
    Body: string
}

我在 Firebase 上的数据结构:

- 通知
- Q6cQqz0OVRPCq17OWb (RecipientUId)
- LtH7QZlWVUcIpNqb-O9
- Body:"You have a notification."
- 标题:"Notification Title"

现在我需要推送通知列表 (notReqs: INotReq[])。
我应该像这样使用for循环吗?

  addMultipleNotification(notificationRequestArray: INotReq[]){    
    notificationRequestArray.forEach(notificationRequest => {
      this.addNotification(notificationRequest);
    });
  }

这是一种不好的做法吗? 或者有更好的方法吗?

你有(至少)另外两种可能性:

  1. 使用update() method which writes multiple values to the Database at once. See also here.

    addMultipleNotification(notificationRequestArray: INotReq[]){
        const fireNots = firebase.database().ref('/notifications');
        var updates = {};
        notificationRequestArray.forEach(notificationRequest => {
            var newKey = fireNots.child(notificationRequest.RecipientUId).push().key;
            updates['/notifications/' + newKey] = {
                Title: notificationRequest.Title,
                Body: notificationRequest.Body
            };
        });
        return firebase.database().ref().update(updates).then(() => {...})
    }
    
  2. 并行使用Promise.all() that will run all the asynchronous push()操作和"returns a single Promise that fulfills when all of the promises passed as an iterable have been fulfilled":

    addMultipleNotification(notificationRequestArray: INotReq[]){
        const fireNots = firebase.database().ref('/notifications');
        var promises = [];
        notificationRequestArray.forEach(notificationRequest => {
    
            promises[fireNots.child(notificationRequest.RecipientUId).push({
                Title: notificationRequest.Title,
                Body: notificationRequest.Body
            })]
    
        });
        return Promise.all(promises).then(() => {...})
    }
    

请注意,这两种方法之间存在重要区别:

  • 通过使用update(),同步更新是原子的:要么所有更新都成功,要么所有更新都失败。

  • 另一方面,如果您使用 Promise.all(),一些推送可能会失败(例如,特定节点的安全规则阻止写入)但其他推送会成功。


此外,请注意,这两种方法的优点是您确切地知道何时完成对数据库的所有写入,因此您可以在.then(() => {...}) 方法(通知最终用户,重定向到另一个页面等)。