Putte
Putte

Reputation: 328

Replace current Firestore document

I've creating a program where you can enter up to 6 persons when registering. And once ur online on the application you can change the names of the persons using textfields. And when I'm clicking on save the program will simply insert the data into Firestore, but thats where the problem occurs.

It insert the data in a new document, and not in the current one. Which is a problem.

So how can I replace documents using Firestore?

Here is my code:

 @IBAction func SaveData(_ sender: Any)
    {
        let authentication = Auth.auth().currentUser?.uid

        //Replacing persons
        db.collection("users").document(authentication!)
        .collection("Person").addDocument(data:
        [
           "Name1": person1.text!,
           "Name2": person2.text!,
           "Name3": person3.text!,
           "Name4": person4.text!,
           "Name5": person5.text!,
           "Name6": person6.text!
         ], completion: { (err) in
                    if err != nil
                    {
                        print("Error replacing persons!")
                        return
                    }
                    else
                    {
                        print("Succeded!")
                    }
            })
    }

When I'm "replacing" the data with the new one, it creates a new document, and not replacing the current one. How can I accomplish that?

Upvotes: 0

Views: 1669

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598797

Every time you call addDocument Firestore will create a new document, as the name of the function implies. To replace the contents of an existing document you must:

  1. Have a reference to that specific document.
  2. Call setData() on that reference.

So say that you want to update the names in a document called Person1:

db.collection("users").document(authentication!)
.collection("Person").document("Person1").setData([
   "Name1": person1.text!,
   "Name2": person2.text!,
   "Name3": person3.text!,
   "Name4": person4.text!,
   "Name5": person5.text!,
   "Name6": person6.text!
 ], completion: { (err) in
        if err != nil
        {
            print("Error replacing persons!")
            return
        }
        else
        {
            print("Succeded!")
        }
})

See the documentation up setting data for a document. You can also update a document, which means that only the fields that you specify are changed. For more on this, see update data in the same documentation page.

Upvotes: 3

Related Questions