Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Bulk update with .push()
* Send a bulk update to Firebase from an array or an object literal.
* When .push() is called on a Firebase reference without a parameter passed no
* trip to the server is made.
* ex:
* var childRef = ref.push();
* A reference is returned which has a push-id that can be returned by calling .name().
* Because of this, we can create an object with push-ids as keys and send to Firebase
* with one .set() method.
* This function takes in a Firebase reference and a collection to bulk update. The
* colleciton can either be an Array or an Object. If an Object is used, its keys
* are ignored and push-ids are used instead.
* @param {Firebase Reference} ref
* @param {Array or Object} collection
* @returns a Promise that is fulfilled through the onComplete argument
function bulkUpdate(ref, collection) {
// object to hold the bulk update
var batch = {};
// Using a ES6 promise here, use a library or polyfil for compatibility
var deferred = Promise.defer();
// using Object.keys will allow us to iterate over an array or object
Object.keys(collection).forEach(function(key) {
// get the push id from the child reference, no server trip is made here
var pushId = ref.push().key();
// get the value from the collection
var itemValue = collection[key];
// using the pushId, assign the value to the bulk update object
batch[pushId] = itemValue;
// send the bulk update to Firebase
ref.update(batch, function onComplete(arg) {
// if the argument is null then it's a successful update
if(arg === null) {
} else {
// if the argument is not null then it is an error
return deferred.promise;
// example:
var ref = new Firebase('https://<your-firebase>');
var itemArray = ['Hello', 'World'];
bulkUpdate(ref, itemArray).then(function(arg) {
}).catch(function(error) {
var itemObj = {
'item1': 'Hello',
'item2': 'World'
// This will only send the values and ignore the keys
bulkUpdate(ref, itemObj).then(function(arg) {
}).catch(function(error) {
Copy link

alexbjorlig commented Jan 28, 2017

Great demo. But you don't need to wrap the firebase update function in a promise, the functions now returns a promise thus the code can be simplified..

Copy link

octalmage commented May 21, 2017

This is awesome, thanks!

Copy link

pawar-aniket commented Aug 23, 2017

Awesome snippet ! Thanks !

Copy link

sabinbajracharya commented Oct 12, 2017

On Line number 31 of bulkUpdate.js, key is not a function anymore, so it's var pushId = ref.push().key;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment