【问题标题】:How to get a single document from firestore?如何从 Firestore 获取单个文档?
【发布时间】:2021-10-16 20:48:04
【问题描述】:

根据 firebase 的文档,您可以使用 get() 非常简单地获取文档

但由于某种原因,在我的代码中它总是显示没有这样的文档,即使它确实存在,这就是我正在做的:

useEffect(() => {

    console.log(user, "This is the user UID:"+user.uid)
    const userDoc = db.collection('usuarios').doc(user.uid);
    const doc = userDoc.get();

    if (!doc.exists) {
        console.log('No such document!');
    }
    
    else {
    userDoc
    .onSnapshot(snapshot => {
      
       const tempData = [];
       snapshot.forEach((doc) => {
         
         const data = doc.data();
         tempData.push(data);
 
       });
       setUserData(tempData);
     })
    }
}, [user]);

这是console.log() 显示的内容:

这就是它在 firebase 中的样子:

【问题讨论】:

  • 最常见的原因是文档 ID 中有一个不可见的字符,例如它之前或之后的空格。我建议使用 console.log("'"+doc.id+"'") 之类的内容打印数据库中的所有文档 ID,以查看不匹配的原因。
  • 不是这样,当我使用 auth.createUserWithEmailAndPassword 创建一个新用户时,我还根据 UID 为该用户创建一个文档,如下所示:db.collection('usuarios').doc(auth.user.uid).set 并在文档中添加 uid .

标签: reactjs firebase google-cloud-firestore


【解决方案1】:
const doc = userDoc.get();

if (!doc.exists) {

.get 返回一个 Promise,因此您正在检查 Promise 上的 .exists 属性,即 undefined。您需要等待该承诺解决,或者使用.then

userDoc.get().then(doc => {
  if (!doc.exists) {
    // etc
  }
});

或者将您的代码放入 async 函数和 await 承诺:

const doc = await userDoc.get();

if (!doc.exists) {
  // etc
}

【讨论】:

    【解决方案2】:

    如果您使用的是 firebase 8 网页版,userDoc.get() 会返回一个承诺,而不是文档:

    
    userDoc.get().then((doc) => {
      if (!doc.exists) {
        console.log('No such document!');
      } else {
        const tempData = [];
        const data = doc.data();
        tempData.push(data);
        setUserData(tempData)
        console.log('it worked')
      }
    }).catch((error) => {
      console.log("Error getting document:", error);
    });
    
    

    您可以在https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises 中获取有关 Promise 的更多信息。

    【讨论】:

      【解决方案3】:

      在您的代码中,您使用 get 方法来获取用户数据并且 get 不提供快照。另外,您错过了 get() 将返回一个承诺,因此您必须使用 async-await 或 .then 等来处理。

      useEffect(() => {
          console.log(user, "This is the user UID:"+user.uid);
          getUser(user.uid).then(userData => {
            setUserData(userData);
          });
      }, [user]);
      
      const getUser = async (id) => {
        try {
          const user = await db.collection('usuarios').doc(id).get();
          const userData = user.data();
          return userData;
        } catch (err){
          console.log('Error during get user, No such document!');
          return  false;
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-19
        • 2018-09-03
        相关资源
        最近更新 更多