简体   繁体   中英

How can I check if a document contains a value inside a Firestore array?

I'm using Flutter and Firestore, where is this database I'm trying to be able to see if a value exists inside an array, but I only found solutions that didn't work for me, sometimes they were in another language, but I want to be able to see if a value exists inside an array in a document.

for example, I want to check if the user id userID1 is inside the array miembros marked in red in the following image

阵列的示例图像

the idea is that I can do an if to add the value userID1 if it doesn't exist in the miembros array. actually thank you very much for any help

If you just need to check if an array contains a specific value, then you can use arrayContains as shown below:

FirebaseFirestore.instance
  .collection('grupos')
  .where('miembros', arrayContains: 'ValueToCheck')
  .get()
  .then(...);

However, you can use arrayUnion() instead that will add the value if it's missing else it won't:

Firestore.instance
  .collection('grupos')
  .document('grupoId4')
  .updateData({ 'array':FieldValue.arrayUnion('ValueToAddInArray') });

I found the solution, it turns out that the following can be done when one knows the document ID.

firestoreRef.where(FieldPath.documentId, isEqualTo: docID).snapshots();

by adding in where the FieldPath.documentId, isEqualTo: docID we can search based on the document id, after this we can do a forEach or whatever is estimated in the case.

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