André Kuhlmann
André Kuhlmann

Reputation: 4668

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 predefined set of properties.

let data = {
  country: 'US',
  language: 'English'
}

Is there some function inside the Firebase Admin SDK that can create all documents at once, without iterating through the array of documentIds?

Upvotes: 0

Views: 939

Answers (2)

Jason Berryman
Jason Berryman

Reputation: 4898

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);
})

Upvotes: 3

Sam Stern
Sam Stern

Reputation: 25134

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 batch
var 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

Upvotes: 2

Related Questions