【问题标题】:Query array of object in firestore查询firestore中的对象数组
【发布时间】:2021-07-30 13:37:02
【问题描述】:

我有一个名为 employees 的集合,其中包括文档,每个文档都包含一些数据,以及一个名为 orgsanizations 的对象数组,例如:

orgsanizations: [
{
orgId: 'org1',
registrationDate: '08/05/2021',
status: 'pending'
},
{
orgId: 'org2,
registrationDate: '12/01/2021',
status: 'approved'
}
];

我正在尝试检索 employees 中包含 orgsanizations 中的 orgId === org1 的所有文档,这是我尝试做的,但一直返回空数组。

  const allEmployees = async () => {
    const employeesList = db.collection('employees');
    const snapshot = await employeesList
      .where('orgsanizations', 'array-contains', { orgId: 'org1' })
      .get();
    if (snapshot.empty) {
      console.log(snapshot.empty);
    } else {
      snapshot.forEach((doc) => {
        console.log(doc.data());
      });
    }
  };
};

是否有解决方案或应该开始考虑将结构更改为其他内容? 提前致谢

【问题讨论】:

    标签: firebase google-cloud-firestore database-design nosql


    【解决方案1】:

    您无法使用array-contains 检查地图的内容。有几个解决方案...

    1. 创建第二个名为orgIds 的数组,其中仅包含orgId 字符串。然后,您可以找到包含这些 orgId 的任何文档。为此,您需要将orgId 写入地图和orgIds 数组。
    2. 创建employee 文档的organizations 子集合并使用collectionGroup 查询。
    {
      organizations: [
        {orgId: 'org1', registrationDate: '08/05/2021', status: 'pending'},
        {orgId: 'org2', registrationDate: '12/01/2021', status: 'approved'}
      ],
      orgIds: ['org1', 'org2']
    }
    
    const employeesList = db.collection('employees');
    const snapshot = await employeesList
    .where('orgIds', 'array-contains', 'org1')
    .get();
    

    您可能还想将您的 registrationDate 更改为时间戳或 ISO8601 字符串,以便对它们进行排序(如果需要)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-17
      • 2019-02-24
      • 2019-12-24
      • 2020-07-09
      • 1970-01-01
      • 2020-04-09
      • 2018-03-26
      相关资源
      最近更新 更多