繁体   English   中英

如何从 Firestore 中检索数据

[英]How to retrieve data from firestore

给定这个 Data structure ,我如何从 firestore 检索我想要的数据数组。 我尝试使用代码片段中的代码检索数据,但是遇到以下错误: Invalid document reference. Document references must have even number of segments but user_data/.../run has 3 Invalid document reference. Document references must have even number of segments but user_data/.../run has 3

 onAuthStateChanged(auth, (user) => { if (user) { setUser(user.uid); } else { console.log("no user found") } }) //Retrieve user entries const colRef = doc(db, 'user_data', user, "run"); const q = query(colRef) onSnapshot(q, (snapshot) => { const user_data = [] snapshot.docs.forEach((doc) => { user_data.push({...doc.data()}) //put the data into an array }) if (bool === false) { setArr(user_data); setBool(true) } })

您收到该错误是因为您在返回 CollectionReference 实例的路径上使用doc() ,它应该用于获取 DocumentReference 实例。

const colRef = doc(db, 'user_data', user, "run");

上面的代码尝试将“db/user_data/user/run”CollectionReference 实例分配给 colRef,但错误地使用了doc()方法。
请记住,firestore 以集合-文档-子集合-文档等方式保存数据。 这意味着db应该是您的数据库根引用, user_data应该是根集合,而user应该是user_data集合中的文档。

更改您的代码以对应于该模式,如下所示:

const docReference = doc(db, "aRootCollection", "documentId"); // Get the document reference.
const docSnapshot = await getDoc(docReference); // Get a snapshot of the document.
const documentData = docSnapshot.data(); // Get the data of the snapshot. In your case, this would return the "run" array.

无需使用 Query 来完成您要完成的工作。 确保您熟悉Promises和/或async await并正确处理所有可能的异常。

确保您阅读了Firestore 官方文档 写的很好,有例子。

PS 尽量与您的报价保持一致,以提高可读性。

看看这个数据结构。数据结构

const aDocmentId = "hH8FfavuIKCwaSQPKmFY"; // The document Id you wish to reference.
const docReference = doc(firestore, `users/${aDocmentId}`); // Getting the Document Reference.
const docReference2 = doc(firestore, "users", "hH8FfavuIKCwaSQPKmFY"); // Same thing but static, with different syntax.
const docSnapShot = await getDoc(docReference); // Get the Document Snapshot.
const docData = docSnapShot.data(); // This will be { name: 'myName', age: 25, rentedMovies: [ 'Burn After Reading', 'Interstellar' ] }
for(const field in docData) { // Loop through all key-value pairs in docData.
   console.log(`${field}: ${docData[field]}`); // Log "Field: value", for every key-value pair.
}

上面的代码将记录以下内容:

name: 'myName'
age: 25
rentedMovies: Burn After Reading,Interstellar

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM