简体   繁体   English

Firestore 通过数组的字段值进行查询

[英]Firestore to query by an array's field value

I'm trying to run a simple query, where I search for a document that contains a value inside an object array.我正在尝试运行一个简单的查询,在其中搜索包含 object 数组中的值的文档。

For instance, look at my database structure:例如,看看我的数据库结构:

火库数据库

I want to run a query similar to this:我想运行类似这样的查询:

db.collection('identites').where("partyMembers", "array-contains", {name: "John Travolta"})

What is the correct way to achieve this, is it even possible with Firestore?实现这一目标的正确方法是什么,Firestore甚至可以吗?

Thanks.谢谢。

As Frank has explained in his answer it is not possible, with array-contains, to query for a specific property of an object stored in an array.正如弗兰克在他的回答中解释的那样,使用数组包含来查询存储在数组中的对象的特定属性是不可能的。

However, there is a possible workaround: it is actually possible to query for the entire object , as follows, in your case:但是,有一种可能的解决方法:在您的情况下,实际上可以查询整个 object ,如下所示:

db.collection('identites').where("partyMembers", "array-contains", {id: "7LNK....", name: "John Travolta"})

Maybe this approach will suit your needs (or maybe not....).也许这种方法会满足您的需求(或者可能不会....)。

The array-contains operations checks if an array, contains a specific (complete) value. array-contains操作检查数组是否包含特定(完整)值。 It can't check if an array of objects, contains an item with a specific value for a property.它无法检查对象数组是否包含具有特定属性值的项目。

The only way to do your query, is to add an additional field to your document with just the value you want to query existence on.进行查询的唯一方法是在文档中添加一个附加字段,其中仅包含您要查询存在的值。 So for example: partyMemberNames: ["John Travolta", "Olivia Newton"] .例如: partyMemberNames: ["John Travolta", "Olivia Newton"]

If you want to extract name: "John Travolta" from "partyMembers" array in a document.如果要从文档中的“partyMembers”数组中提取名称:“John Travolta”。 you can achieve this by some similar approach in which you can loop through all arrays in a document to find this name.您可以通过一些类似的方法来实现这一点,您可以循环遍历文档中的所有数组以查找此名称。

 const [names, setNames] = React.useState([]) const readAllNames = async() => { const snapshot = await firebase.firestore().collection('identites').doc(documentID).get() const filterData = snapshot.data().question.map(val => val.name === "John Travolta" ? val : null) setNames( filterData.filter(e=>e) ); }
This technique is used in perticular Document as we are giving .doc(documentID) This way you can get all the arrays having name: "John Travolta" in names constant. 当我们给出 .doc(documentID) 时,此技术用于特定文档中,这样您可以获得名称为“John Travolta”的所有数组,名称为常量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM