【发布时间】:2021-07-08 16:19:33
【问题描述】:
您好,我目前被阻止,因为我无法从具有 references 值的集合中获取所有记录。
我想从集合events 中获取所有记录(它有效),但是当我想合并与categoryId 关联的category 信息时,我的代码不再有效。
export const getEventsRequest = async () => {
const output = [];
const data = await firebase.firestore().collection('events').get();
data.forEach(async (doc) => {
const {
name,
address,
city,
duration,
level,
startDate,
maxPeople,
categoryId,
} = doc.data();
const { name: categoryName, color } = (
await firebase.firestore().collection('categories').doc(categoryId).get()
).data();
output.push({
name,
address,
city,
duration,
level,
startDate,
maxPeople,
category: { name: categoryName, color },
});
});
return output;
};
React Native 项目中的示例测试
const [events, setEvents] = useState([]);
const [isEventsLoading, setIsEventsLoading] = useState(false);
const getEvents = async () => {
setEvents([]);
setIsEventsLoading(true);
try {
const evts = await getEventsRequest();
setEvents(evts);
setIsEventsLoading(false);
} catch (e) {
console.error(e);
}
};
useEffect(() => {
getEvents();
}, []);
console.log('events', events);
输出
events Array []
预期
events Array [
{
name : "blabla",
address: "blabla",
city: "blabla",
duration: 60,
level: "hard",
startDate: "13/04/2021",
maxPeople: 7,
category: {
name: "Football",
color: "#fff"
},
},
// ...
]
我不知道是否有更简单的方法来检索这种数据(例如mongo DB上有populate方法)。
提前感谢您的回答。
【问题讨论】:
标签: javascript reactjs firebase react-native google-cloud-firestore