使用动态键从 Firestore 中删除字段 [英] Delete a field from Firestore, with a dynamic key
问题描述
我正在尝试从 Firestore 中的文档中删除单个字段字段的键保存在一个变量中,例如
I am trying to delete a single field from a Document in Firestore The Key of the field is held in a variable e.g.
var userId = "random-id-1"
在文档中,我有一个成员字段,结构如下:
In the document I have a field of members structured like this:
{
members:{
random-id-1:true,
random-id-2:true
}
}
我想删除random-id-1:true
,但保留random-id-2:true
如果不获取整个成员对象并编写更新的对象,这怎么可能?
How is this possible without getting the entire members object and writing an updated object?
我已经尝试过这个,但是我收到错误:Document引用必须有偶数个段
I have tried this, however I get the error: Document references must have an even number of segments
我也试过这个:
db.collection('groups').doc(this.props.groupId).set({
members: {
[userId]: firebase.firestore.FieldValue.delete()
}
},{merge: true})
但是我收到错误:Function DocumentReference.update() 调用了无效数据.FieldValue.delete() 只能出现在你更新数据的顶层
感谢您的帮助
推荐答案
我已经成功删除了这样的字段:
I have managed to delete a field like this:
let userId = "this-is-my-user-id"
let groupId = "this-is-my-group-id"
db.collection('groups').doc(groupId).update({
['members.' + userId]: firebase.firestore.FieldValue.delete()
})
这是使用此处
如果有任何替代方法,请告诉我
Please let me know if there are any alternative methods to this
谢谢
这篇关于使用动态键从 Firestore 中删除字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!