首页 > 解决方案 > 如何访问引用 Firebase 中另一个对象的对象

问题描述

我的 Firebase .json 看起来像:

"Employees": {
    "Employee1" : {
      "Activities": {
        "Activity1": true
      },
      "age" : 61,
      "name" : "Employee1"
     },
     .
     .
     .
    //other employees
}
"Activities": {
     "Activity1": {
       "name": "Name of Activity1",
       "value": 2,
       "cost": 2
     },
     .
     .
     .
     //other activities
}

我想要做的是显示 Employee1。在这种情况下,Employee1 在活动下只有 Activity1。我需要显示 Employee1 数据,包括其活动的数据。我正在使用 React,我正在使用 firebase.database().ref()on('value', function(snapshot))显示来自 Firebase 的数据。任何帮助将不胜感激。

标签: reactjsfirebasefirebase-realtime-databasereference

解决方案


在 NoSQL 数据建模中,您应该毫不犹豫地复制数据,即以这种方式进行非规范化,使您的查询更容易,更重要的是,更快。

因此,在您的情况下,您可以按如下方式修改数据结构:

"Employees": {
    "Employee1" : {
      "Activities": {
        "Activity1": {
          "name": "Name of Activity1",  // <- add the details of the activity here
          "value": 2,
          "cost": 2
         },
      },
      "age" : 61,
      "name" : "Employee1"
     },
     .
     .
     .
    //other employees
}
"Activities": {
     "Activity1": {
       "name": "Name of Activity1",
       "value": 2,
       "cost": 2
     },

这种技术的一个缺点是您必须保持两个节点同步,但这可以通过使用该update()方法轻松完成,请参阅文档


推荐阅读