How to push multiple items in Firebase?

Viewed 2085

I have an array of objects. What I try to do is to push all items to a specific location inside database, because with push call each item will be assigned an unique id.

I try to place Firebase push inside a loop but I think it's somehow not right to do so. (web app here)

const array = [{title: 'one'},{title:'two'}, {title: 'three'}]

array.map(item => {
          FirebaseRef.child(`boards/${boardId}/containers`).push(item)
})
1 Answers

The following, using the update() method, will work:

const array = [{ title: 'one' }, { title: 'two' }, { title: 'three' }]

var updates = {};
array.map(item => {
     var newPostKey = firebase.database().ref().child(`boards/${boardId}/containers/`).push().key;
     updates[`boards/${boardId}/containers/` + newPostKey] = item;
});
firebase.database().ref().update(updates);
Related