【问题标题】:fazer variavel sair do IFfazer variavel sair do IF
【发布时间】:2022-10-04 22:20:05
【问题描述】:

我正在尝试在用户会话电子邮件和 firestore 数组中的电子邮件之间进行比较。也就是说,我想在数据库中搜索登录电子邮件,如果找到任何电子邮件,请将一些信息带到屏幕上,例如姓名和姓氏。

我什至设法进入数组并进行比较,但我不能让“var UserName”离开 IF 的 {}

有人能帮我吗?

我的代码是:

    const [data, setData] = useState([]);
    const getUsers = () => {
      firestore()
      .collection("users")
      .get()
      .then((querySnapshot) => {
        let userFirestore = [];
        querySnapshot.forEach((doc) => {
            
            const usuario = {
              id: doc.id,
              nome: doc.data().nome,
              sobrenome: doc.data().sobrenome,
              email: doc.data().email,
              profissao: doc.data().profissao,
            }
            userFirestore.push(usuario);

        });
        
        userFirestore.forEach(function (item, indice, array) {
          if (item.email === user.email){ //user.email brings the email of the logged in user
            var nomeUsuario = item.nome
            console.log(nomeUsuario) //UserName brings the result I expected
          } 

        });
    })
    .catch((error) => console.log(error));
    }

【问题讨论】:

    标签: javascript arrays react-native google-cloud-firestore


    【解决方案1】:

    您可以使用查询来获取包含当前用户电子邮件的文档,而不是获取整个集合,如下所示:

    firestore()
      .collection("users")
      .where("email", "==", user.email)
      .get().then((querySnapshot) => {
        if (querySnapshot.empty) {
          console.log("User not found")
        } else {
          const user = querySnapshot.docs[0].data();
          console.log(user)
        }
      })
    

    更好的是,如果您使用用户的 UID 作为 Firestore 文档 ID(强烈推荐),那么您可以按 ID 获取该单个文档,如下所示:

    firestore()
      .collection("users")
      .doc(user.uid) // < user.uid must be defined
      .get()
      .then((snapshot) => {
        console.log(snapshot.data())
      })
    

    【讨论】:

      猜你喜欢
      • 2021-01-08
      • 2021-10-04
      • 1970-01-01
      • 2015-02-06
      • 2018-08-12
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      • 2013-08-16
      相关资源
      最近更新 更多