ditto
ditto

Reputation: 41

Remove/Delete array index in Firebase

when I delete a book from the collection view it deletes it from the UI but the deletion is not reflected in my firestore database. Ive tried .delete() but it deletes the entire book array. I only want to delete the book selected on collection view. Im currently trying to pass my book array let userBooks: [UserBooks] = [] as a parameter.

enter image description here

fileprivate func removeUserBooksTest(userBooks: UserBooks) {
    guard let uid = Auth.auth().currentUser?.uid else { return }
    Firestore.firestore().collection("books").document(uid).updateData(["books": FieldValue.arrayRemove([userBooks])]) { (error) in
        if let error = error {
            print(error)
            return
        }
    }
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        //Create a option menu as an action sheet
        let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        
        //Add the cancel button
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        optionMenu.addAction(cancelAction)
        
        //Add the remove book button
        let removeBook = UIAlertAction(title: "Remove Book", style: .destructive) { (action: UIAlertAction) in
            
    
            self.removeUserBooksTest(userBooks: self.userBooks[indexPath.item])
            self.userBooks.remove(at: indexPath.item)
            self.collectionView.deleteItems(at: [indexPath])
        }
        optionMenu.addAction(removeBook)
        
        //Display the menu
        present(optionMenu, animated: true)
    }
}

Upvotes: 0

Views: 856

Answers (1)

Felipe Kimio
Felipe Kimio

Reputation: 31

the problem is

Firestore.firestore().collection("books").document(uid).updateData(["books": FieldValue.arrayRemove([userBooks])])

The uid must be the document id wS2KCDkSpy0n... instead of user uid

And is better if you use collection -> document -> document instead collection -> document -> array cuz books already is a bunch of book :) thinking like that we can delete using this example https://firebase.google.com/docs/firestore/manage-data/delete-data

db.collection(collectionName).document(documentId).delete() { err in
if let err = err {
    print("Error removing document: \(err)")
} else {
    print("Document successfully removed!")
}}

Where collectionName = "books" and documentId = "wS2KCDkSpy0n"

Upvotes: 1

Related Questions