CollectionGroup 查询返回空结果

CollectionGroup Query returning an empty result

我正在开发一款应用程序,该应用程序可帮助用户在附近的药店搜索他们想要的药物,然后显示有库存药品和价格的药店列表。

这是数据库的结构:

Firestore-root
  |
  --- pharmacies (collection)
        |
        --- $pharmacyId (document)
               |
               --- medicine (sub-collection)
                     |
                     --- $medicineId
                           |
                           --- name: "Aspirin"
                           |
                           --- inStock: true
                           |
                           --- price: 500

我曾经在 CollectionGroup 上查询 FireFoo 以获取有“阿司匹林”库存的药房,例如,我得到了促进创建索引并创建了所需的索引,但查询结果为空。

这里是查询:

async function run() {
  const query = await db.collectionGroup("medicine")
    .where("name", "==", "Aspirin")
    .where("inStock", "==", "true")
    .get();
  return query;
}

这里有一些图片用于说明:

Pharmacies collection with 2 Pharmacy documents

medicine subcollection inside the 1st pharmacy document

medicine subcollection inside the 2nd pharmacy document

CollectionGroup index

Query Result

以下查询中的问题:

async function run() {
  const query = await db.collectionGroup("medicine")
    .where("name", "==", "Aspirin")
    .where("inStock", "==", "true")
    .get();
  return query;
}

在于第二次 .where() 调用。在数据库中,当您搜索包含字符串值的文档时,您的 inStock 字段包含一个布尔值,这是不正确的。要解决这个问题,只需使用:

async function run() {
  const query = await db.collectionGroup("medicine")
    .where("name", "==", "Aspirin")
    .where("inStock", "==", true) //No double quotes
    .get();
  return query;
}