Firestore update only one field

Delphian picture Delphian · Dec 12, 2017 · Viewed 43.4k times · Source

I have a database. The sequence is: collections - document - hashmaps. For example:

users - the name of the collection

users.uid - the name of the document

Hashmap the document consists of a lot of hashmaps user data Hashmap Hashmap etc

Hashmap: the name of user is the key and telephone, location etc are the values. I need to update only one field(location) for one username, but can't understand how do this?

I tried the next way (update phone number for alex):

User user = new User();
user.setPhone(131902331);

Map<String,RealmObject> userMap = new HashMap<>();
userMap.put("alex",user);

          mFirebaseFirestore
                  .collection("users")
                  .document(mFirebaseAuth.getUid())
                  .set(userMap, SetOptions.merge())
                  .addOnSuccessListener(new OnSuccessListener<Void>() {
                      @Override
                      public void onSuccess(Void aVoid) {
                          LOG.info("Success");
                      }
                  })
                  .addOnFailureListener(new OnFailureListener() {
                      @Override
                      public void onFailure(@NonNull Exception e) {
                          LOG.error("Failure "+e.toString());
                      }
                  });

What I am doing wrong?

Answer

Frank van Puffelen picture Frank van Puffelen · Dec 12, 2017

When you call set() on a document, the existing contents of that documents are replaced with the data you pass in.

If you want to only update the values of the field you specify in a map, use update():

mFirebaseFirestore
  .collection("users")
  .document(mFirebaseAuth.getUid())
  .update(userMap)

See the Firestore documentation on updating a document.