在雲公司的FireStore有三個寫操作:差異與{合併:真正}和更新
1)添加
2)設置
3)更新
在文檔中說,使用set(object, {merge: true})
會將對象與現有對象合併。
當您使用update(object)
時會發生同樣的情況所以有什麼區別?谷歌將重複邏輯似乎很奇怪。
在雲公司的FireStore有三個寫操作:差異與{合併:真正}和更新
1)添加
2)設置
3)更新
在文檔中說,使用set(object, {merge: true})
會將對象與現有對象合併。
當您使用update(object)
時會發生同樣的情況所以有什麼區別?谷歌將重複邏輯似乎很奇怪。
我的理解的不同方式:
set
沒有合併將覆蓋一個文件或創建它,如果它不存在尚未
set
與合併將更新文檔中的字段或創建它,如果它不存在
update
將更新字段,但將失敗,如果文檔不存在
create
將創建文檔,但失敗,如果該文件已經存在
還有中的數據類型你提供set
和update
的差異。
對於set
你總是必須提供的文件型數據:
set(
{a: {b: {c: true}}},
{merge: true}
)
隨着update
您還可以使用現場路徑用於更新嵌套值:
update({
'a.b.c': true
})
另一個不同之處(延長Scarygami的答案)在「設置合併」和「更新」之間,是在使用嵌套值時。
,如果你有一個文檔的結構是這樣的:
{
"friends": {
"friend-uid-1": true,
"friend-uid-2": true,
}
}
,並希望以此來增加{"friend-uid-3" : true}
:
db.collection('users').doc('random-id').set({ "friends": { "friend-uid-3": true } },{merge:true})
會導致這樣的數據:
{
"friends": {
"friend-uid-1": true,
"friend-uid-2": true,
"friend-uid-3": true
}
}
然而
update
使用此:
db.collection('users').doc('random-id').update({ "friends": { "friend-uid-3": true } })
會導致這樣的數據:
`{
"friends": {
"friend-uid-3": true
}
}`
但如果你發現在API中'create'方法? – ZuzEL
https://cloud.google.com/nodejs/docs/reference/firestore/0.8.x/DocumentReference#create for node.js.看來web API沒有這種方法。不知道你在哪個平臺:) – Scarygami
你可以提到的另一個區別是'set'在文檔形狀的數據上運行,其中'update'採用字段路徑和值對。這意味着你可以使用'update'對深層嵌套值進行更改,這對set''來說更麻煩。例如:'set({a:{b:{c:true}}},{merge:true})'vs'update('a.b.c',true)'。 –