【问题标题】:CollectionGroup Query returning an empty resultCollectionGroup 查询返回空结果
【发布时间】:2021-11-20 08:43:27
【问题描述】:

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

这是数据库的结构:

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

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

这里是查询:

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

【问题讨论】:

  • 是的,它是空的,当我在 VS 代码上调试时,当我将鼠标悬停在查询变量上时,它显示大小为 0。 @Alex 的回答解决了我的问题,这是对引号的滥用。

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


【解决方案1】:

以下查询中的问题:

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;
}

【讨论】:

  • 查询现在有效,它返回医学下的 2 个文档。太感谢了!!!我认为我应该在每个药物文档中添加一个包含药房名称或 id 的字段,以便在用户搜索时知道要显示哪些药房
  • 很高兴听到这个消息。不客气,麦兹。是的,你绝对可以做到。
猜你喜欢
  • 1970-01-01
  • 2021-03-18
  • 2019-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
  • 2012-10-17
相关资源
最近更新 更多