Adding list of data in Firebase

2019-09-10 08:48发布

The following code works as expected. But I have 2 questions:

// Save default Account Types
var refTypes = this.housesRef.child(key + "/memberaccounttypes/");
refTypes.push({ name: 'Checking', icon: '0' });
refTypes.push({ name: 'Savings', icon: '0' });
refTypes.push({ name: 'Credit Card', icon: '0' });
refTypes.push({ name: 'Debit Card', icon: '0' });
refTypes.push({ name: 'Investment', icon: '0' });
refTypes.push({ name: 'Brokerage', icon: '0' });
  1. With this approach, am I doing several trips to Firebase, one for each push?
  2. Is there a more efficient, best-practice, way to save the following data all at once?

I'm using Firebase SDK 3

1条回答
倾城 Initia
2楼-- · 2019-09-10 09:19

Each call to push in this way will indeed result in a roundtrip to Firebase. You can easily verify this by checking the "Web Sockets" pane on network tab of your browser debug tools.

If you'd like to run this as a single update, you can combine them into a multi-location update with:

var refTypes = this.housesRef.child(key + "/memberaccounttypes/");
var updates = {};
updates[refTypes.push().key] = { name: 'Checking', icon: '0' };
updates[refTypes.push().key] = { name: 'Savings', icon: '0' };
updates[refTypes.push().key] = { name: 'Credit Card', icon: '0' };
updates[refTypes.push().key] = { name: 'Debit Card', icon: '0' };
updates[refTypes.push().key] = { name: 'Investment', icon: '0' };
updates[refTypes.push().key] = { name: 'Brokerage', icon: '0' };
refTypes.update(updates);

Note that this will hardly save any time/bandwidth, since the Firebase client pipelines requests.

查看更多
登录 后发表回答