iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 25
1
Modern Web

我或許沒那麼懂 Web系列 第 25

Cloud Firestore β (17): Batch

今天來研究怎麼在 Cloud Firestore 進行 Batch 吧。先把相關的 API 列出來:

  • firebase.firestore.Firestore
    • batch() returns firebase.firestore.WriteBatch
  • firebase.firestore.WriteBatch
    • set(documentRef, data, options) returns firebase.firestore.WriteBatch
    • update(documentRef, ...var_args) returns firebase.firestore.WriteBatch
    • delete(documentRef) returns firebase.firestore.WriteBatch
    • commit() returns Promise containing void

使用方式就是透過 Firestore.batch() 去建立一個 WriteBatch 物件,用該物件來記錄要批次操作的寫入動作。正如同昨天講述的 Transactions,我們可以透過這個物件提供的 set()update()delete() 去操作 Document Reference 物件,這些方法的參數和Document Reference 物件的同名方法相同,只是會插入 Document Reference 物件作為第一個參數。

當我們寫完要在這次批次進行的動作時就可以透過 WriteBatc.commit() 方法將這個批次提交,也就是送出 request。

使用 batch 的好處在於多個寫入操作可以只使用一次 request 完成,減少來回等候的時間。這種功能非常適合用在需要大量遷移資料到 Cloud Firestore 的情境。一個 BatchWrite 最多可以包含五百個寫入操作。

let batch = db.batch();

let txgRef = db.collection('cities').doc('TXG')
batch.set(nycRef, {name: 'Taichung City'})

let khhRef = db.collection('cities').doc('KHH')
batch.update(sfRef, {'population': 5000000})

let tpeRef = db.collection('cities').doc('TPE')
batch.delete(tpeRef)

batch.commit().then(function() {
  console.log('Batch successfully committed!')
}).catch(function() {
  console.log('Batch failed.')
})

上一篇
Cloud Firestore β (16): Transactions
下一篇
Cloud Firestore β (18): 離線資料 - 1
系列文
我或許沒那麼懂 Web31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言