Created
March 26, 2018 14:37
-
-
Save choipd/10e5fee0eadb470a6768670753f38963 to your computer and use it in GitHub Desktop.
Firestore batch update
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function updateCollection(db, collectionRef, newData, batchSize) { | |
// console.log('updateCollection') | |
var query = collectionRef.orderBy('__name__').limit(batchSize); | |
return new Promise(function(resolve, reject) { | |
updateQueryBatch(db, query, batchSize, newData, resolve, reject); | |
}); | |
} | |
function updateQueryBatch(db, query, batchSize, newData, resolve, reject) { | |
// console.log('updateQueryBatch') | |
query.get() | |
.then((snapshot) => { | |
// console.log('updateQueryBatch: snapshot.size = ', snapshot.size) | |
// When there are no documents left, we are done | |
if (snapshot.size == 0) { | |
return 0; | |
} | |
// Delete documents in a batch | |
var batch = db.batch(); | |
snapshot.docs.forEach(function(doc) { | |
batch.update(doc.ref, newData); | |
}); | |
return batch.commit().then(function() { | |
return snapshot.size; | |
}); | |
}).then(function(numUpdated) { | |
if (numUpdated <= batchSize) { | |
resolve(); | |
return; | |
} | |
// Recurse on the next process tick, to avoid | |
// exploding the stack. | |
process.nextTick(function() { | |
updateQueryBatch(db, query, batchSize, newData, resolve, reject); | |
}); | |
}) | |
.catch(reject); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment