You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firestore WhereArrayContains代码查询无结果但控制台查询正常

Firestore数组包含查询无结果问题排查

问题描述

Firestore的patients集合中文档包含字符串数组字段hospitals,通过代码查询数组中包含指定字符串的文档时返回0条结果,但在Firebase控制台执行相同查询可成功获取数据。其他增改操作均正常,已确认查询用的UserData.doctor_hospital_id值与目标文档的hospitals数组值完全匹配。

数据结构说明

patients集合的文档包含以下关键字段:

  • hospitals: 字符串数组
  • EditedAt: 用于排序的时间字段
  • 其他字段:Name、FirstName、MiddleName等用户信息字段

问题代码

int limit = 6;
int startingIndex = 0;

void GetPatientsInHospital()
{
    CollectionReference collectionRef = FirebaseAPI.firestore.Collection("patients");
    Query query = collectionRef.WhereArrayContains("hospitals", UserData.doctor_hospital_id).OrderByDescending("EditedAt").Limit(limit).StartAt(startingIndex);

    query.GetSnapshotAsync().ContinueWith((querySnapshotTask) =>
    {
        if (querySnapshotTask != null && querySnapshotTask.Exception != null && !string.IsNullOrEmpty(querySnapshotTask.Exception.Message))
            Debug.LogError(querySnapshotTask.Exception.Message);
        if (querySnapshotTask != null && querySnapshotTask.Result != null && querySnapshotTask.Result.Documents != null)
        {
            foreach (DocumentSnapshot doc in querySnapshotTask.Result.Documents)
            {
                Patient patient = new Patient();
                patient.fullname = doc.GetValue<string>("Name");
                patient.Patient_Data.first_name = doc.GetValue<string>("FirstName");
                patient.Patient_Data.middle_name = doc.GetValue<string>("MiddleName");
                patient.Patient_Data.last_name = doc.GetValue<string>("LastName");
                patient.Patient_Data.phoneNumber = doc.GetValue<string>("Phone");
                patient.Patient_Data.email = doc.GetValue<string>("Email");
                patient.Patient_Data.serial_number = doc.GetValue<string>("SerialNumber");
                patient.Patient_Data.nationalID = doc.GetValue<string>("NationalID");
                hospitalPatients.Add(doc.Id, patient);
            }

            Reload_PatientScroller_Data();
            loadingSpinner.SetActive(false);
        }
    });
}

Firestore安全规则

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read;
      allow create;
      allow update;
    }
  }
}

问题原因及解决方法

核心问题

代码中使用了StartAt(startingIndex),传入的数字0会让Firestore寻找EditedAt字段值等于0的文档作为查询起始点。但EditedAt是时间戳/日期类型字段,不存在值为0的文档,导致查询返回空结果。

解决方案

  • 首次查询无需分页起始条件:如果是第一次加载数据,直接移除StartAt(startingIndex):
Query query = collectionRef.WhereArrayContains("hospitals", UserData.doctor_hospital_id)
                           .OrderByDescending("EditedAt")
                           .Limit(limit);
  • 分页查询使用游标:如果需要实现分页,需记录上一次查询返回的最后一个文档快照,作为下一次查询的StartAfter参数:
// 假设lastDoc是上一次查询的最后一个DocumentSnapshot
Query query = collectionRef.WhereArrayContains("hospitals", UserData.doctor_hospital_id)
                           .OrderByDescending("EditedAt")
                           .StartAfter(lastDoc)
                           .Limit(limit);

内容的提问来源于stack exchange,提问作者Ash10

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 10:23:14