在Firestore中更新文档时,我想保留大部分文档,但是要更改一个包含对象的属性。
是)我有的
{
name: "John Doe",
email: "[email protected]",
friends: {
a: {...},
b: {...},
c: {...},
d: {...},
e: {...},
f: {...},
}
}
现在,我有一个新的朋友对象,例如 {x: ..., y: ..., z: ...}
我想覆盖friends
文档的树,但保留所有其他字段。
我想要它看起来像什么
{
name: "John Doe",
email: "[email protected]",
friends: {
x: {...},
y: {...},
z: {...},
}
}
但是,如果我做一个 firestore.doc(...).update({friends: {...}}, { merge: true })
我现在得到什么
{
name: "John Doe",
email: "[email protected]",
friends: {
a: {...},
b: {...},
c: {...},
d: {...},
e: {...},
f: {...},
x: {...},
y: {...},
z: {...},
}
}
我知道我可以进行两次更新,即删除该字段然后再次设置它,或者我可以阅读文档,更改对象并保存而不合并。
但是,在保留其余文档不变的情况下,是否存在一种聪明的方式来覆盖对象(地图)?
由于使用的是update()
方法,因此只需要调用它而无需合并选项。
firestore.doc(...).update({friends: {...}})
请注意,它update()
具有两个不同的签名:
update(data: UpdateData)
和
update(field: string | FieldPath, value: any, ...moreFieldsAndValues: any[])
如果您传递给该方法的第一个参数是一个对象,它将认为您使用了第一个签名,因此只能传递一个参数。这样做
firestore.doc(...).update({friends: {...}}, { merge: true })
应该会产生以下错误:
“错误:函数DocumentReference.update()需要1个参数,但是用2个参数调用。 ”
另一方面,您可以这样称呼:
firestore
.collection('...')
.doc('...')
.update(
'friends.c',
'Tom',
'email',
'[email protected]',
'lastUpdate',
firebase.firestore.FieldValue.serverTimestamp()
);
最后,要完整,请注意,如果您执行以下操作(传递一个字符串)
firestore
.collection('...')
.doc('...')
.update(
'a_string'
);
您将收到以下错误
“错误:函数DocumentReference.update()至少需要2个参数,但是使用1个参数调用。 ”
这是有道理的:-)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句