[英]Firestore to query by an array's field value
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"})
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) ); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.