How to check if an array in a firestore document is empty?

Viewed 4443

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.

enter image description here

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!

3 Answers

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);

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.

    • If hasProblems==false, then toggle it to true and add the problem to the list.
    • else no need to toggle, just add the new problem to the list.
    • If problems are to be removed later on, then check for the list to get empty. Once it is empty, then toggle hasProblems back to false.

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.

There is no way to check with firestore query if an array is empty or not.
But, you can follow these steps:

  • Query the data with range filters:
_postsStream = await _firestore.collectionGroup('posts')
   .where('timestamp', isGreaterThanOrEqualTo: _start)
   .where('timestamp', isLessThanOrEqualTo: _end)
   .snapshots();
  • After fetching the data, iterate over all the DocumentSnapshot and check if problems array is empty or not.
Related