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
CodePudding user response:
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') });
CodePudding user response:
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.