【问题标题】:Removing one item from map removes all items从地图中删除一项会删除所有项目
【发布时间】:2020-02-11 03:14:16
【问题描述】:

我的 Firestore 数据库中有一个简单的地图,如下所示:

我正在尝试从 following 地图中仅删除一项,如下所示:

func removeUserFromFriendsList(friendToRemove id: String, _ currentUserId: String, completion: @escaping(Bool)->()) {
    let friendsRef = db.collection(USERS_COLLECTION).document(currentUserId)
    friendsRef.updateData([
        USER_FOLLOWING: FieldValue.arrayRemove([id])
    ]) { (error) in
        if error != nil {
            completion(false)
        }
        completion(true)
    }
}

但不是删除带有ID 的项目,而是删除following 中的整个列表

【问题讨论】:

  • 我认为您正在更新整个集合而不是删除该项目。尝试获取要删除的朋友的引用,然后使用 friendsRef.delete()

标签: swift google-cloud-platform google-cloud-firestore


【解决方案1】:

我猜问题是我在following级别,并没有指定要正确删除的id。所以它只是删除了following 中的所有内容。 指定 id 并像这样删除它就可以了:

func removeUserFromFriendsList(friendToRemove id: String, _ currentUserId: String, completion: @escaping(Bool)->()) {
        let friendsRef = db.collection(USERS_COLLECTION).document(currentUserId)
        friendsRef.updateData([
            USER_FOLLOWING + "." + id : FieldValue.delete()
        ]) { (error) in
            if error != nil {
                completion(false)
            }
            completion(true)
        }
    } 

USER_FOLLOWING 是数据库中字段的名称(又名“以下”)。

添加+“.”+和id只是指定我们要删除哪个id,所以看起来像这样:

following.AP3ENXgW2mhvaWsUeDOxchYaAGm1 <--- the field and id to delete

然后使用FieldValue.delete 将其完全删除。

编辑: 答案在这里:

How to remove an array item from a nested document in firebase?

【讨论】:

    【解决方案2】:

    按照Firebase documentation中的示例

    let friendsRef = db.collection(USERS_COLLECTION).document(currentUserId)
    
    // Atomically removes an ID from the "USER_FOLLOWING" array field.
    friendsRef.updateData([
        "USER_FOLLOWING": FieldValue.arrayRemove([id])
    ])
    

    如果这不是您的选择,则解决方法 是从文档中读取整个数组,在内存中对其进行修改,然后完全更新修改后的数组字段。

    【讨论】:

    • 我不确定USER_FOLLOWING 代表什么,但我认为您需要为@JohnDoah 提到的尝试更新的字段提供正确的路径。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多