簡體   English   中英

Firstore 一次創建多個文檔

[英]Firstore create multiple documents at once

我已經給出了我想添加到 Firestore 的文檔ID數組。

let documentIds = [
  'San Francisco',
  'New York',
  'Las Vegas'
]

每個文檔都應該有一組預定義的屬性。

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

Firebase Admin SDK 中是否有一些功能可以一次創建所有文檔,而無需遍歷 documentIds 數組?

這應該有所幫助。 Sam 的回答會讓您很好地理解如何使用批量寫入。 請務必查看他鏈接到的文檔。

我不想讓薩姆不高興。 他昨天修好了我的筆記本電腦:-)

使用數組設置批處理

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

您可以進行批量寫入。 您仍然需要遍歷文檔以將它們全部添加到批處理對象,但這將是一個單一的網絡調用:

例子:

// 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM