在云公司的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)'。 –