How to update a single firebase firestore document

JavascriptFirebaseGoogle Cloud-Firestore

Javascript Problem Overview


After authenticating i'm trying to lookup a user document at /users/, then i'd like to update the document with data from auth object as well some custom user properties. But I'm getting an error that the update method doesn't exist. Is there a way to update a single document? All the firestore doc examples assume you have the actual doc id, and they don't have any examples querying with a where clause.

firebase.firestore().collection("users").where("uid", "==", payload.uid)
  .get()
  .then(function(querySnapshot) {
      querySnapshot.forEach(function(doc) {
          console.log(doc.id, " => ", doc.data());
	      doc.update({foo: "bar"})
      });
 })

Javascript Solutions


Solution 1 - Javascript

You can precisely do as follows (https://firebase.google.com/docs/reference/js/v8/firebase.firestore.DocumentReference):

var db = firebase.firestore();

db.collection("users").doc(doc.id).update({foo: "bar"});

Solution 2 - Javascript

Check if the user is already there then simply .update, or .set if not:

    var docRef = firebase.firestore().collection("users").doc(firebase.auth().currentUser.uid);
    var o = {};
    docRef.get().then(function(thisDoc) {
        if (thisDoc.exists) {
            //user is already there, write only last login
            o.lastLoginDate = Date.now();
            docRef.update(o);
        }
        else {
            //new user
            o.displayName = firebase.auth().currentUser.displayName;
            o.accountCreatedDate = Date.now();
            o.lastLoginDate = Date.now();
            // Send it
            docRef.set(o);
        }
        toast("Welcome " + firebase.auth().currentUser.displayName);
    });
}).catch(function(error) {
    toast(error.message);
});

Solution 3 - Javascript

in your original code changing this line

doc.update({foo: "bar"})

to this

doc.ref.update({foo: "bar"})

should work

but a better way is to use batch write: https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes

Solution 4 - Javascript

-- UPDATE FOR FIREBASE V9 --

In the newer version of Firebase this is done like this:

import { doc, updateDoc } from "firebase/firestore";

const washingtonRef = doc(db, "cities", "DC");

// Set the "capital" field of the city 'DC'
await updateDoc(washingtonRef, {
  capital: true
});

Solution 5 - Javascript

You only need to found official ID of document, code here!

    enter code here
    //Get user mail (logined)
    val db = FirebaseFirestore.getInstance()
    val user = Firebase.auth.currentUser
    val mail = user?.email.toString()

       //do update
       val update = db.collection("spending").addSnapshotListener { snapshot, e ->
                val doc = snapshot?.documents
                doc?.forEach {
                    //Assign data that I got from document (I neet to declare dataclass) 
                    val spendData= it.toObject(SpendDt::class.java)
                    if (spendData?.mail == mail) {
                        //Get document ID
                        val userId = it.id
                        //Select collection
                        val sfDocRef = db.collection("spendDocument").document(userId)
                        //Do transaction
                        db.runTransaction { transaction ->
                            val despesaConsum = hashMapOf(
                                "medalHalfYear" to true,
                            )
                            //SetOption.merege() is for an existing document
                            transaction.set(sfDocRef, despesaConsum, SetOptions.merge())
                        }
                    }

                }
            }
}
data class SpendDt(
    var oilMoney: Map<String, Double> = mapOf(),
    var mail: String = "",
    var medalHalfYear: Boolean = false
)

Solution 6 - Javascript

correct way to do this is as follows; to do any data manipulation in snapshot object we have to reference the .ref attribute

 firebase.firestore().collection("users").where("uid", "==", payload.uid)
  .get()
  .then(function(querySnapshot) {
      querySnapshot.forEach(function(doc) {
          console.log(doc.id, " => ", doc.data());
          doc.ref.update({foo: "bar"})//not doc.update({foo: "bar"})
      });
 })

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJim JonesView Question on Stackoverflow
Solution 1 - JavascriptJuan LaraView Answer on Stackoverflow
Solution 2 - JavascriptRonnie RoystonView Answer on Stackoverflow
Solution 3 - JavascriptprefView Answer on Stackoverflow
Solution 4 - JavascriptPeter PalmerView Answer on Stackoverflow
Solution 5 - JavascriptRaimonView Answer on Stackoverflow
Solution 6 - Javascriptnavaneeth001View Answer on Stackoverflow