首页 > 解决方案 > 从 Firestore 获取子集合的 JSON 响应

问题描述

我正在尝试合并所有医生的信息:

{"id": "...", "firstName": "...", "lastName": "..."}


我的 Firestore 数据树如下所示:

在此处输入图像描述

我正在写我GET的:

app.get('/doctors/cardiology/doctors', async (req, res) => {
  try {
    const doctorsDetailsQuerySnapshot = await db.collection("doctors").doc("cardiology").listCollections();
    const doctors: any[] = [];
    doctorsDetailsQuerySnapshot.forEach((doc1) => {
      doctors.push({
        id: doc1.id,
        data: doc1.doc(doc1.id).collection(doc1.id),
      });
    });
    res.status(200).json(doctors);
  } catch (error) {
    res.status(500).send(error);
  }

实际输出:

[
    {
        "id": "919505294523",
        "data": {
            .... metadata....
        }
    },
    {
        "id": "919505294525",
        "data": {
            .... metadata....
        }
    }
]

预期输出:

[
  {
      "id": "919505294523",
      "data": {
          "id": "919505294523",
          "firstName": "B.F.",
          "lastName": "Skinner"
      }
  },
  {
      "id": "919505294525",
      "data": {
          "id": "919505294525",
          "firstName": "Carl",
          "lastName": "Rogers"
      }
  }
]

有人可以帮助我的新手头脑吗?几乎卡了2个小时。

标签: jsonfirebaseexpressgoogle-cloud-firestore

解决方案


作为您有关数据库结构的问题的答案。

现在你的结构是这样的:

\collection(doctors)
   \document(specialization)
      \collection(doctorId)
         \document(doctorID)

因此,您有一个集合,doctors其中包含每个专业的文档(例如cardiology),并且在每个专业下,您有每个医生的集合,其中包含带有医生字段的文档。

相反,我会建议一个更简单、更直接的结构,如下所示:

\collection(Doctors)
  \document(doctorID)

我的建议是制作一个集合,Doctors其中包含每个医生的文档。在文档的字段中,您可以包含已经存在的字段(firstName、id、lastName)并添加更多字段specialization(例如“专业:心脏病学”)。

这是一个更简单的实现,您仍然可以使用where('specialization', '==', 'cardiology'). where()可以在此处找到有关该方法的更多信息


推荐阅读