Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript Firebase Firestore,当必须以编程方式解决子字段名称时,如何更新嵌套在子字段中的数组?_Typescript_Firebase_Google Cloud Firestore - Fatal编程技术网

Typescript Firebase Firestore,当必须以编程方式解决子字段名称时,如何更新嵌套在子字段中的数组?

Typescript Firebase Firestore,当必须以编程方式解决子字段名称时,如何更新嵌套在子字段中的数组?,typescript,firebase,google-cloud-firestore,Typescript,Firebase,Google Cloud Firestore,堆栈: 火基火库 打字稿4 反应本机0.63 其想法是为内容管理系统构建跟踪/取消跟踪系统 例如,用户希望遵循与TypeScript语言相关的帖子 我们可以想象: fitlerId1 == 'Language' item1 == 'TypeScript' 用户后跟的过滤器项存储在Firestore中的用户文档中: // Collection: users // Document: userId { name: 'Joe', follow: { filterId1: [ite

堆栈:

  • 火基火库
  • 打字稿4
  • 反应本机0.63
其想法是为内容管理系统构建跟踪/取消跟踪系统

例如,用户希望遵循与TypeScript语言相关的帖子

我们可以想象:

fitlerId1 == 'Language'
item1 == 'TypeScript'
用户后跟的过滤器项存储在Firestore中的用户文档中:

// Collection: users
// Document: userId
{
  name: 'Joe',
  follow: {
    filterId1: [itemId1, itemId2, itemId3]
    filterId3: [itemId4]
    // ...
  },
  scores: { 
    filterId1: {itemId1: 123} 
    // ...
  }
}
字段未初始化为null。此用户没有filterId2字段,有些用户甚至没有follow子字段

我们需要实现的是切换跟随功能,以便:

如果filter1中有item1,我们需要将其删除

否则,我们需要:

  • 将其添加到当前数组中
  • 或者,如果字段(可能还有子字段)不存在或为空,则创建数组
这是我目前的代码:

//取消跟踪。。。
if(fieldValue&&Array.isArray(fieldValue)&&fieldValue.includes(itemId)){
ref.update({[`follow.${filterId}`]:firebase.firestore.FieldValue.arrayRemove(itemId)})
}
//跟随
否则{
ref.set({follow:{[filteridasstring]:[itemId]},{merge:true})
}
我不确定[
follow.${filterId as string}
]是否可以这样工作,但是如果我不放[],我会得到一个typescript错误

我也不确定set merge是否会删除当前的数组

编辑:测试后,我可以确认它确实擦除了阵列。所以我们最好区分第一次创建(在这里我们可以使用集合合并)和字段更新(在这里我们将使用firebase.firestore.FieldValue.arrayUnion(itemId))