【发布时间】:2018-12-24 19:37:03
【问题描述】:
我正在尝试使用 Firebase/Firestore 获得这样的输出
"topRecipes": [
{
"id": "LGvuYa0pN2432fd",
"created": 1531480386994,
"prep": 25,
"cook": 2
"ingredients": [
{
"ingName": "golden caster sugar",
"weight": 300,
},
{
"ingName": "butter",
"weight": 300,
},
{
"ingName": "self-raising flour",
"weight": 300,
},
],
"recipeName": "Butterfly cupcakes",
"username": "John Doe",
"uid": "c1Mi03C7KxOpKceazn8GLovGGW73",
},
]
我使用 Firestore 引用对象(如外键)来填充内部(成分)数组,但我觉得我尝试过的东西非常混乱,甚至无法正常工作。
constructor() {
super()
this.state = { selectedIndex: 0, topRecipes: [] };
this.recipesInit = [];
}
componentWillMount() {
let recipeList;
db.collection("Recipes").orderBy("created", "asc").get().then((qss) => {
qss.forEach((doc) => {
const { created, prep, cook, recipeName, username, uid, flavorListRef } = doc.data();
recipeList = {
id: doc.id,
created: created.Timestamp,
prep: prep,
cook: cook,
recipeName: recipeName,
username: username,
uid: uid,
}
if (flavorListRef) {
let combineRecipes = { ...recipeList, flavorList:[] };
flavorListRef.collection("flavorList").get().then((sqss) => {
sqss.forEach( docs => {
const { ingName, weight } = docs.data();
combineRecipes.flavorList.push({
ingName: ingName,
weight: weight,
})
}) //forEach
})
.then(() => {
this.recipesInit.push( ...this.recipesInit, combineRecipes )
this.setState({ topRecipes: this.recipesInit })
})
.catch(err => console.error(err));
}
}) //forEach
})
.catch(err => console.error(err));
}
结果当前生成第一个结果对象两次,然后是其余结果。
Object 0 {
Array []
}
Object 0 {
Array []
}
Object 1 {
Array []
}
我想知道是否有更好的方法从 Firestore 获取数据,以及如何正确地将这些数据操作为 json 输出。
我的数据库当前已设置 /食谱/asdkjaskda/flavorList/kjhasdkjhasd
【问题讨论】:
标签: javascript firebase react-native foreach google-cloud-firestore