iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 17
1
Modern Web

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

Cloud Firestore β (9): 更新資料

  • 分享至 

  • twitterImage
  •  

今天就來研究怎麼開始用 SDK 在 Cloud Firestore 更新資料吧。

昨天有提到,如果使用文件參照的 set() 方法時,若參照的位置原本就有文件時,原本的資料就會整個被覆蓋掉。那我們只想更新局部資料,而沒有要完全取代的話,該怎麼做呢?那就使用 update() 方法吧!示例如下:

let taipeiRef = db.collection('cities').doc('taipei')

taipeiRef.update({
    capital: true
})
.then(function() {
    console.log('Document successfully updated!')
})
.catch(function(error) {
    // The document probably doesn't exist.
    console.error('Error updating document: ', error)
})

一樣先針對文件建立參照,然後在 update() 方法中輸入資料物件,裡面是想要更新的欄位與其資料。後面的 .then().catch() 方法昨天有提過,今天就不再贅述。值得一提的是,要注意當更新的參照並不存在時,是會跳錯的,也就是會執行 .catch() 裡的回呼函示。

另外,若是要更新嵌套的欄位,也就是 Map 資料型別下的欄位時,可以用 . 去指定,可以直接看下面的示例:

let peterRef = db.collection('users').doc('peter')
peterRef.set({
    name: 'Peter',
    age: 42
    favorites: { 
        food: 'Pizza', 
        color: 'Blue', 
    }
})

peterRef.update({
    'age': 43,
    'favorites.color': 'Green'
})
.then(function() {
    console.log('Document successfully updated!')
})

若是更新的欄位是屬於 Array 資料型別時,則是用 firebase.firestore.FieldValue 下的 arrayUnion 去加入資料、arrayRemove 去移除資料:

let taichungRef = db.collection('cities').doc('taichung')

taichungRef.update({
    districts: firebase.firestore.FieldValue.arrayUnion('fengyuan')
})

taichungRef.update({
    regions: firebase.firestore.FieldValue.arrayRemove('tongluo')
});

如果是希望日期時間資料型別的欄位,能夠填寫伺服器當下的時間作為值時,可以使用 firebase.firestore.FieldValue.serverTimestamp()

let docRef = db.collection('objects').doc('some-id')

docRef.set({
    created_at: firebase.firestore.FieldValue.serverTimestamp()
})

docRef.update({
    updated_at: firebase.firestore.FieldValue.serverTimestamp()
})

上一篇
Cloud Firestore β (8): 建立資料
下一篇
Cloud Firestore β (10): 刪除資料
系列文
我或許沒那麼懂 Web31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言