How to update a single firebase firestore document

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"})
      });
 })

Solution 1:

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:

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:

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