【问题标题】:RN/ Firestore - How to use Firestore reference object to populate a nested arrayRN/ Firestore - 如何使用 Firestore 引用对象来填充嵌套数组
【发布时间】: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


    【解决方案1】:

    看来我要做的就是

    改变这个 this.recipesInit.push( ...this.recipesInit, combineRecipes )

    this.recipesInit.push( combineRecipes )

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-30
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 2017-01-01
      • 2020-08-28
      • 1970-01-01
      • 2018-05-25
      相关资源
      最近更新 更多