简体   繁体   中英

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? 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": ...

I was expecting a boolean for existence but did not find any. 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. There is no other way to query Firestore, and your code will need to deal with that 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.

By the way, your use of await is incorrect. firestore().collection('users') returns a CollectionReference immediately with no promise. where() will return Query object. And get() will return a promise with a QuerySnapshot:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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