Home > Net >  How to remove a certain field from map cloud firestore?
How to remove a certain field from map cloud firestore?

Time:10-02

I continue to develop a directory application and now I need to delete a specific line in the map from cloud firestore.There is my database: screenshot I need to remove field with key "2324141" or change its value. I know about this method:

"2324141": FieldValue.delete()

But how do I get into the map and delete field or change the value? thanks!

Here is my model of Object:

class ObjectInFB: Codable {
var objectFromPartsCatalogueListCode: String?
var countOfCurrentObjectInShoppingCart: Int = 1}

Here is func, where i save object in users shoppingBag:

    func addToUserShoppingCartFB(user: User?, object: ObjectInFB, count: Int){
    
    guard let user = user else { return }
    
    let objectReadyToBeWriten = [
        "UserEmail":"\(user.email!)",
        "shoppingCart" : ["\(object.objectFromPartsCatalogueListCode!)" : FieldValue.increment(Int64(count))]] as [String : Any]
    db.collection("users")
        .document("\(user.uid)")
        .setData(objectReadyToBeWriten, merge: true)
        { err in
            if let err = err {
                print("Error adding document: \(err)")
            } else {}
        }
}

And after the user in their cart in the application clicks "remove from cart" I want to delete an object from their cart in Firebase. I can only remove any field from the document, but how can I remove a field from the nested ShoppingCart?

       func removeShoppingCartFB(object: ObjectInFB, user: User?){
    db.collection("users").document(user!.uid).updateData([
        "shoppingCart": ["\(object.objectFromPartsCatalogueListCode!)" : FieldValue.delete()],
    ]) { err in
        if let err = err {
            print("Error updating document: \(err)")
        } else {
            print("Document successfully updated")
        }
    }
}

CodePudding user response:

If the goal is to delete a field within a map, it can be accessed through dot notation. For example suppose your structure looks like this

users
   uid_0
      UserEmail: "[email protected]"
      shoppingCart  (a map)
         2324141: 10
         122323424: 13

and we want to remove the 2324141 field. Here's the Swift code to do that

let myCollection = self.db.collection("users")
let myDoc = myCollection.document("uid_0")
myDoc.updateData( ["shoppingCart.2324141": FieldValue.delete(),
]) { err in
    if let err = err {
        print("Error updating document: \(err)")
    } else {
        print("Document successfully updated")
    }
}
  • Related