【问题标题】:How can I Update Document in Collection firebase如何更新 Collection firebase 中的文档
【发布时间】:2021-10-04 11:31:03
【问题描述】:

所以我有这个头像,我想不仅在个人资料上显示头像,而且在 Feed 和其他一些页面上显示。在我的“用户”集合中,我有一个名为“photoURL”的对象。我正在尝试做的是,当有人添加或更改个人资料图片时,“photoURL”应该在集合中自动更新。

我背后的逻辑是我需要它来在其他页面上显示照片,为此我必须将它保存到集合中以便我可以访问它。 也许我的逻辑是错误的,我不知道,但我没有找到其他方法,我认为这是最简单的。

这是用户收藏代码:

 function onSignUp() {
    firebase
      .auth()
      .createUserWithEmailAndPassword(email, password)
      .then((result) => {
        firebase
          .firestore()
          .collection("users")
          .doc(firebase.auth().currentUser.uid)
          .set({
            name,
            email,
            role: isTeacher ? "pädagoge" : "parent",
            photoURL: null,
          });
        console.log(result);
      })
      .catch((error) => {
        console.log(error);
      });

头像选择器代码:

async function handleFileInputChange(e) {
    const files = e.target.files;
    const file = files[0];

    const storage = firebase.storage();
    const usersImageRef = storage
      .ref()
      .child(`users/${user.uid}/profilepicture.jpg`);

    const snap = await usersImageRef.put(file);

    const donwloadURL = await snap.ref.getDownloadURL();
    setDownloadURL(donwloadURL);

    // Save photoUrl in user collection
    // -> {name : "...", email : "...", role : "...", photoUrl : "..."}
    
    await firebase.auth().currentUser.updateProfile({ photoURL: donwloadURL });
    setProfilePictureUrl(donwloadURL);
  }

我在 firbase doc 上看到了这个例子:

db.collection("users").doc("frank").update({
  favorites: {
    food: "Ice Cream"
  }
}).then(function() {
  console.log("Frank food updated");
});

但我需要代码来动态执行此操作,但我不确定如何。

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore


    【解决方案1】:

    您可以像这样将.then() 添加到您的handleFileInputChange() 函数中:

    await firebase.auth().currentUser.updateProfile({ photoURL: downloadURL }).then(()=>{
        db.collection("users").doc("frank").update({
            userProfileImage: downloadURL
      }).catch((err)=>{
          //handle errors
      });
    }).catch((err)=>{
          //handle errors
     }); 
    

    也要注意 downloadURL 的拼写。

    【讨论】:

    • 好的,我尝试了类似的方法,但是 doc() 里面应该放什么我的意思是我显然没有 Frank,我在想是否应该把 uid 放在里面?
    • "frank" 将是特定用户的文档 ID
    • 在您的情况下,这是用户的 uid(firebase.auth().currentUser.uid)
    • 是的,但我不需要特定用户,我需要让它更动态。我有几个用户如何查看当前用户?这样我就不用一一写每个用户了。
    【解决方案2】:
     firebase
              .firestore()
              .collection("users")
              .doc(firebase.auth().currentUser.uid)
              .update({
                name:name,
                email:email,
                role: isTeacher ? "pädagoge" : "parent",
                photoURL: photourl,
              });
    

    【讨论】:

      猜你喜欢
      • 2019-10-06
      • 2021-12-19
      • 2020-10-23
      • 2018-09-15
      • 2020-05-24
      • 2021-02-05
      • 2019-02-06
      • 2020-03-19
      • 1970-01-01
      相关资源
      最近更新 更多