Firstore create multiple documents at once

送分小仙女□ 提交于 2020-04-17 18:33:10

问题


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?


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



回答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 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



来源:https://stackoverflow.com/questions/49012176/firstore-create-multiple-documents-at-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!