Reputation: 237
I'm building out an app in flutter and I want to run a query to determine if the array in my firestore document is empty. Is there a way to do this?
Here is a picture of my data structured in firestore.
I know there is an arrayContains method but I'm not sure on how to check for an empty array. Here is my current code.
_postsStream = await _firestore
.collectionGroup('posts')
.where('timestamp', isGreaterThanOrEqualTo: _start)
.where('timestamp', isLessThanOrEqualTo: _end)
.where('problems', arrayContains: )
.snapshots();
I left the arrayContains: intentionally empty for now. Please advise on how I would go about implementing this feature. Thanks in advance!
Upvotes: 10
Views: 8888
Reputation: 528
An empty array defaults to [] So this is possible by doing the following: Do not use ' ' for the square brackets
final _database = Firestore.instance;
return _database
.collection('arrays')
.document(arrId)
.where('array', isEqualTo: [])
// .where('array', isNull: true) can be used to check if it's null
.snapshots()
.map(_itemListFromSnapshot);
Upvotes: 20
Reputation: 1122
You cannot do it in firestore currently. What you can do is.
Create a separate property hasProblems which defaults to false.
If the user try to register a problem, then check the flag hasProblems.
This way you can achieve what you want-
postsStream = await _firestore
.collectionGroup('posts')
.where('timestamp', isGreaterThanOrEqualTo: _start)
.where('timestamp', isLessThanOrEqualTo: _end)
.where('hasProblems',isEqualsTo: false)
.snapshots();
Maybe you can have other better solutions, but this is the one that came in my mind. You can follow the solution @mubin986 has given, but once the list gets bigger and bigger, it impacts performance. Cheers, hope it helps.
Upvotes: 3
Reputation: 2286
There is no way to check with firestore query if an array is empty or not.
But, you can follow these steps:
_postsStream = await _firestore.collectionGroup('posts')
.where('timestamp', isGreaterThanOrEqualTo: _start)
.where('timestamp', isLessThanOrEqualTo: _end)
.snapshots();
DocumentSnapshot
and check if problems
array is empty or not.Upvotes: 1