node.js - 在数组子 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);
}
解决方案
如果要在数组中的所有项目中搜索items
与您拥有的值匹配的项目,可以使用array-contains
运算符:
dbRef.where('producto.items', 'array-contains', { producto: req.params.nombre})
但请注意,这仅在数组仅包含producto
每个项目中的字段时才有效。原因是array-contains
(和其他数组级运算符)仅对完整项起作用。
因此,如果项目中producto.items
有多个子字段,并且您想匹配其中一个/一些,则不能使用array-contains
. 在这种情况下,您的选择是:
- 将项目名称存储在单独/附加的数组字段中
product-names
,然后使用array-contains
. - 将数组项存储在子集合中并进行查询。
- 使用映射而不是数组来存储这些值。但是,这会生成许多额外的索引,这既增加了存储成本,也可能使您达到索引数量的限制。
推荐阅读
- git - 如何在我不是所有者的情况下签署我对 Github 存储库的提交?
- php - Laravel:eloquent-sluggable
- javascript - 通过javascript的宽度和高度不起作用?
- ios - 更改 UINavigationItem 可访问性元素顺序
- oracle - 如何将用户输入参数值存储到 PLSQL 中的单独表中
- ios - 用于 Xcode 的 Tesseract:未加载库
- reactjs - 反应选择多个真-逗号分隔值显示
- python - 有没有办法选择 HTML 文件的某个部分并使用 python 将其粘贴到另一个文件中?
- php - 身份证号码不变
- java - 我可以在 Arraylist.contains 方法的参数内查询对象的某个属性吗?