首页 > 解决方案 > 在数组子 Firestore 中搜索

问题描述

如何在这样的数据结构中检索与孩子匹配的所有文档:

{
  [
    id: {
      name: "name",
      products: {
        items: [
          productName: "this is the product Name"
        ]
      }
    }
  ]
}

我尝试比较的参数是products.items[0].productName 中的参数。

这就是我尝试过的方法,但它没有检索到任何东西:

try{
        var data = [];
        const byName = await dbRef.where('producto.items[0].producto', '==', req.params.nombre).get();
        console.log(byName);
        if (byName.empty) {
            console.log('No matching documents.');
            res.send('No matching documents.');
            return;
          }  
          
          byName.forEach(doc => {
            console.log(doc.id, '=>', doc.data());
            data.push(doc.data());
          });

          res.send(data);
    }catch(err){
        res.send(err);
    }

标签: node.jsfirebasegoogle-cloud-firestore

解决方案


如果要在数组中的所有项目中搜索items与您拥有的值匹配的项目,可以使用array-contains运算符

dbRef.where('producto.items', 'array-contains', { producto: req.params.nombre})

但请注意,这仅在数组包含producto每个项目中的字段时才有效。原因是array-contains(和其他数组级运算符)仅对完整项起作用。

因此,如果项目中producto.items有多个子字段,并且您想匹配其中一个/一些,则不能使用array-contains. 在这种情况下,您的选择是:

  • 将项目名称存储在单独/附加的数组字段中product-names,然后使用array-contains.
  • 将数组项存储在子集合中并进行查询。
  • 使用映射而不是数组来存储这些值。但是,这会生成许多额外的索引,这既增加了存储成本,也可能使您达到索引数量的限制

推荐阅读