How to update a single firebase firestore document

2019-03-29 07:10发布

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

2条回答
倾城 Initia
2楼-- · 2019-03-29 07:54

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);
});
查看更多
劫难
3楼-- · 2019-03-29 08:11

You can build a doc reference from the doc.id:

var db = firebase.firestore();

db.collection("users").where("uid", "==", payload.uid)
  .get()
  .then(function(querySnapshot) {
      querySnapshot.forEach(function(doc) {
          console.log(doc.id, " => ", doc.data());
          // Build doc ref from doc.id
          db.collection("users").doc(doc.id).update({foo: "bar"});
      });
 })
查看更多
登录 后发表回答