【问题标题】:Firstore create multiple documents at onceFirestore 一次创建多个文档
【发布时间】:2018-02-27 15:21:03
【问题描述】:

我提供了一组文档 id's,我想将其添加到 Firestore。

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

每个文档都应该有一组预定义的属性。

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

Firebase Admin SDK 中是否有一些功能可以一次创建所有文档,而无需遍历 documentIds 数组?

【问题讨论】:

    标签: javascript node.js google-cloud-firestore


    【解决方案1】:

    这应该会有所帮助。 Sam 的回答将使您很好地了解如何使用批量写入。请务必查看他链接到的文档。

    我不想让 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);
    })
    

    【讨论】:

      【解决方案2】:

      您可以进行批量写入。您仍然需要遍历文档以将它们全部添加到批处理对象中,但这将是一个单一的网络调用:

      例子:

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

      【讨论】:

        猜你喜欢
        • 2018-03-19
        • 2018-11-22
        • 2018-08-24
        • 2018-07-08
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多