首页 > 解决方案 > 将两个具有相同名称的单独文档上传到 Firebase

问题描述

我希望能够在 Firebase 中添加两个具有相同名称的不同文档。现在,如果我尝试这样做,第一个文档就会被覆盖。文档具有不同的值。这就是我现在添加的方式:

let batch = db.batch()

// update listCounter
let userRef = Firestore.firestore().collection("users").document(userID)
batch.updateData(["wishCounter": counter + 1], forDocument: userRef)

// save wishlist with properties
let wishRef = db.collection("users").document(userID).collection("wishlists").document(wishListName).collection("wünsche").document(wish.name)

batch.setData(["name": wish.name, "link": wish.link, "price": wish.price, "note": wish.note, "wishlistIDX": selectedWishlistIdx, "wishCounter": counter, "imageUrl": ""], forDocument: wishRef)
batch.commit { (error) in
    if let error = error {
        Utilities.showErrorPopUp(labelContent: "Wunsch konnte nicht gespeichert werden", description: error.localizedDescription)
    }
}

wishName应始终创建。我不知道更多代码在这里是否有帮助,但如果有请告诉我。在这方面找不到任何东西,所以我对每一个帮助都很满意!

标签: iosswiftfirebasegoogle-cloud-firestore

解决方案


两个文档不可能在同一个集合中具有相同的 ID。ID 在集合中必须是唯一的。我建议重新考虑您的数据库模型,并想出一种方法来以不需要重复 ID 的方式对数据进行建模。通常,您接受由 创建的随机 ID addDocument(),并依赖字段值来查询匹配的文档。


推荐阅读