Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore update only one field

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?

like image 778
Delphian Avatar asked Dec 12 '17 10:12

Delphian


People also ask

How do I update a field in firestore?

Firestore Update Document Field What if we want to just update a value of a specific field in an existing document. To do that, all we have to do is add a third argument to the setDoc() method. It will be a JavaScript object with a single property: merge:true.

How do I increment a value in firestore?

Firestore now has a specific operator for this called FieldValue. increment() . By applying this operator to a field, the value of that field can be incremented (or decremented) as a single operation on the server.


2 Answers

I know it's almost a year old question, but this might help someone. Use dot notation

db.collection("users")   .document("frank")   .update({     "age": 13,     "favorites.color": "Red"   }); 
like image 62
MrAleister Avatar answered Oct 02 '22 16:10

MrAleister


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.

like image 40
Frank van Puffelen Avatar answered Oct 02 '22 14:10

Frank van Puffelen