[英]How to use an array of keys to query multiple documents in Firestore
我有一个网站,用户可以在那里做课程。 当用户启动课程时,我想将课程标识符添加到firestore中的该用户文档。 在网站上,用户拥有自己的个人资料页面。 其中一个部分是正在进行的课程部分,用户可以在其中查看他们当前注册的课程。
我可以在课程开始课程时将课程文档键添加到用户文档的字段中,该字段是包含其他集合中文档的键的字符串数组。
我遇到的问题是尝试显示用户当前在其个人资料中注册的课程。
我认为问题是在渲染屏幕后课程文档会回来。
我已经尝试使用async和await,以确保代码首先完成循环并获取所有课程文档,因此它可以将它们呈现到屏幕上,但这不起作用。
非常感谢您的任何帮助
getEnrolledCareersList = async()=> {
let careersEnrolled = [];
let careersEnrolledTemp = [];
let careersEnrolledDocumentKeys = ["84YU2pLABF6qUvUEuwIm", "kwBaAUwkjTutGTcIKShw"];
await careersEnrolledDocumentKeys.forEach((documentKey) =>{
console.log("documentKey: ", documentKey);
db.collection("...")
.where("courseDocumentKey", "==", documentKey)
.get()
.then(
(querySnapshot) => {
if (querySnapshot.empty) {
// doc.data() will be undefined in this case
console.log("No such document!");
return;
}
querySnapshot.forEach((doc) => {
console.log("getEnrolledCareersList Document data:", doc.data());
const {
courseName,
courseId,
coursePhotoUrl,
courseDocumentKey,
} = doc.data();
careersEnrolledTemp.push({
courseName,
courseId,
coursePhotoUrl,
courseKey: courseDocumentKey,
});
});
},
function(error) {
console.log("Error getting document Error: ", error);
},
);
});
JSX组件:
<div
style={{
// border: "solid #8492A6 5px",
display: "flex",
flexDirection: "column",
//flexWrap: "wrap",
justifyContent: "flex-start",
padding: "0 0%",
}}>
{this.state.currentPaths.map((item, index) => (
<div
style={{
display: "flex",
flexDirection: "row",
padding: "1% 1%",
}}>
<img
alt={"career image"}
src={item.coursePhotoUrl}
/>
<div
style={{
// border:"solid red 1px",
display: "flex",
flexDirection: "column",
justifyContent: "space-evenly",
padding: "0 2%",
}}>
{/*Career Name Label*/}
<label
style={{
// border: "solid #8492A6",
textAlign: "center",
}}>
{item.courseName}
</label>
{/*Career Percentage Completed Label*/}
<label
style={{
// border: "solid #8492A6",
textAlign: "center",
}}>
Percentage
</label>
</div>
</div>
))}
</div>
我最终这样做了,它解决了我的问题。 一位朋友帮助我得到了这个,以及@Doug Stevenson非常感谢。
getCourse = id => db.collection("abc")
.doc(id)
.get();
getEnrolledCareersList = async (courseIds = ["1", "2"]) => {
const requests = courseIds.map(this.getCourse);
const responses = await Promise.all(requests);
const enrolledCourses = responses.map(doc => doc.data());
this.setState({
...this.state,
enrolledCourses,
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.