Firstore Create Multiple Documents At Once
I have given an array of document id's which I want to add to Firestore. let documentIds = [ 'San Francisco', 'New York', 'Las Vegas' ] Each document should have a predefine
Solution 1:
This should help. Sam's answer will give you a good understanding of how to use batch writes. Be sure to check out the documentation that he linked to.
I don't want to upset Sam. He fixed my laptop, yesterday :-)
Setting a batch with an array
let documentIds = [
'San Francisco',
'New York',
'Las Vegas'
]
let data = {country: 'US', language: 'English'}
var batch = db.batch();
documentIds.forEach(docId => {
batch.set(db.doc(`cities/${docId}`), data);
})
batch.commit().then(response => {
console.log('Success');
}).catch(err => {
console.error(err);
})
Solution 2:
You can do a batched write. You'll still need to iterate through the docs to add them all to the batch object, but it will be a single network call:
Example:
// Get a new write batchvar batch = db.batch();
// Set the value of 'NYC'var nycRef = db.collection("cities").doc("NYC");
batch.set(nycRef, {name: "New York City"});
// Update the population of 'SF'var sfRef = db.collection("cities").doc("SF");
batch.update(sfRef, {"population": 1000000});
// Delete the city 'LA'var laRef = db.collection("cities").doc("LA");
batch.delete(laRef);
// Commit the batch
batch.commit().then(function () {
// ...
});
https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes
Post a Comment for "Firstore Create Multiple Documents At Once"