簡體   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