繁体   English   中英

从 swiftui 中的云 firestore 数组中删除元素

[英]delete element from cloud firestore array in swiftui

我在 Firestore Cloud 中的列表 我正在尝试使用 arrayRemove() 从数组中删除一个元素(只有一个),但我的“note”数组中的所有元素都被删除了

注意结构

struct Notes: Identifiable {
    
    var id = UUID().uuidString
    var nom: [String]
}

类别结构

struct Categorys: Identifiable {
    
    var id = UUID().uuidString
    var idDoc: String
    var note: Notes
}

视图模型

class DataManager: ObservableObject {
    
    @Published var note: [Notes] = []
    @Published var cat: [Categorys] = []

    func deleteFields2(cat: Categorys) {
        let db = Firestore.firestore()
        guard let userID = Auth.auth().currentUser?.uid else {return}

        let note = cat.note.nom
        db.collection("Users").document(userID).collection("Categorys").document(cat.idDoc).updateData([
            
            "note": FieldValue.arrayRemove(note)
        
        ]) { err in
            if let err = err {
                print("Error updating document: \(err)")
                
            } else {
                print("Document successfully updated")
                
            }
        }
    }   

要从note数组中删除一个项目,您需要将该数组项目的确切值传递给arrayRemove 您的代码将数组传递给arrayRemove ,因此该代码将删除任何数组,该数组项是具有您指定值的数组 - 屏幕截图中不存在。

要从数组中删除字符串,请将字符串值传递给arrayRemove 例如:

db.collection("Users").document(userID).collection("Categorys").document(cat.idDoc).updateData([    
    "note": FieldValue.arrayRemove("cheese")
])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM