[英]Query for existence of a value in a specific array field - All documents within a collection
The collection structure:集合结构:
users >
name: 'John'
phoneNumbers: ['12345', '67891']
How do I check if a given phone number (example: 999999) exists in any of the phone numbers fields?如何检查给定的电话号码(例如:999999)是否存在于任何电话号码字段中? I have tried:我努力了:
const usersRef = await firestore().collection('users')
const dbResponse = usersRef.where('phoneNumbers', 'array-contains', '999999')
This returns me a huge object starting with "_collectionPath": ...
这返回给我一个巨大的 object 以"_collectionPath": ...
I was expecting a boolean for existence but did not find any.我期待一个 boolean 存在,但没有找到。 Is my query wrong?我的查询错了吗?
When you perform any query at all, you are going to get back a QuerySnapshot containing every document that matches the query.当您执行任何查询时,您将返回一个QuerySnapshot ,其中包含与查询匹配的每个文档。 There is no other way to query Firestore, and your code will need to deal with that QuerySnapshot object.没有其他方法可以查询 Firestore,您的代码将需要处理该 QuerySnapshot object。
The easiest way to find out if any document matched the query without actually having to look through each document snapshot is to simply check if the size property of the QuerySnapshot is greater than 0.找出是否有任何文档与查询匹配而无需实际查看每个文档快照的最简单方法是简单地检查 QuerySnapshot 的size属性是否大于 0。
By the way, your use of await
is incorrect.顺便说一句,您对await
的使用是不正确的。 firestore().collection('users')
returns a CollectionReference immediately with no promise. firestore().collection('users')
立即返回没有 promise 的CollectionReference 。 where() will return Query object. where()将返回查询 object。 And get() will return a promise with a QuerySnapshot: get()将返回带有 QuerySnapshot 的 promise:
const usersRef = firestore().collection('users')
const querySnapshot = await usersRef
.where('phoneNumbers', 'array-contains', '999999')
.get()
if (querySnapshot.size > 0) {
// do something
}
I suggest studying the documentation for more detail on how to execute a query.我建议研究 文档以获取有关如何执行查询的更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.