2

I get some data from firestore. Sometimes when I called to get data, the collection is not created yet. before calling get request, how do I check collection is exists or not?

  Stream<List<ChatModel>> getChat(ChatFieldModel model) {
    var ref = _db.collection('chats');

      return ref
          .document(model.docId)
          .collection('messages')
          .orderBy('timestamp', descending: true)
          .snapshots()
          .map((list) =>
          list.documents.map((doc)=>ChatModel.fromForestore(doc)).toList());
  }
BIS Tech
  • 17,000
  • 12
  • 99
  • 148
  • 1
    You can only determine if a collection exists by reading a document from them. The cheapest way to do that is to read a single document. You just commented on my answer on pretty much the exact same question here: https://stackoverflow.com/questions/54055565/in-dart-flutter-how-can-i-find-out-if-there-is-no-collection-in-the-firestore-d/54057116?noredirect=1#comment104628578_54057116 How is this question different from that one? – Frank van Puffelen Dec 06 '19 at 01:04

6 Answers6

3

I posted this before

 final snapshot = await firestore.collection(roomName).getDocuments();
 if (snapshot.documents.length == 0) {
 //doesnt exist
 }

Hope this helps

2

Collections are not created or deleted independently of documents. When you create a document and specify it as being part of a certain collection, that collection is created automatically if it does not already exist. Similarly, when you remove the last document in a collection, that collection will automatically be deleted. So there is really no circumstance where you need to worry about whether a collection has been created or not, and you have no explicit control over creating or deleting collections.

Kris
  • 3,091
  • 20
  • 28
1

Usually a collection in Firestore gets deleted if no Documents exist in it.

However, there might be cases where you want to keep a history of the collection modification events, or let's say for some reason prevent Collections from being deleted.

Or for example, you want to know when a collection was created in the first place. Normally, if the Documents are deleted, and then the Collection gets created again, you will not know the initial creation date.

A workaround I can think of is the following:

Initialize each collection you want with a Document that will be specifically for keeping generic info about that collection.

For example: enter image description here

This way, even if all other Documents in the Collection are deleted, you'll still keep the Collection in addition to some info that might be handy if In the future you need to get some history info about the Collection.

So to know if a Collection exists of no, you can run a query that checks for a field in Info Documents (eg CollectionInfo.exists) to know which Collections have been already created.

Waelmas
  • 1,894
  • 1
  • 9
  • 19
  • However, please keep in mind that this will have an extra cost every extra Read/Write operation. – Waelmas Dec 06 '19 at 10:51
1

This is for the most recent update

 final snapshot = await FirebaseFirestore.instance
   .collection('collection name').get();

 if ( snapshot.size == 0 ) {
   print('it does not exist');
 }
General Grievance
  • 4,555
  • 31
  • 31
  • 45
0

Feb 2022

Get QuerySnapshot and return querySnapshot.docs.isNotEmpty or isEmpty

 Future<bool> isItems() async {
    CollectionReference collectionReference =
        _firestore.collection("users").doc(_user!.uid).collection("cart");
    QuerySnapshot querySnapshot = await collectionReference.get();
    return querySnapshot.docs.isNotEmpty;
  }
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 19 '22 at 11:38
0
await FirebaseFirestore.instance
    .collection('collectionName')
    .limit(1) 
    .get() 
    .then((snapshot) { 
        if (snapshot.size == 0) {
            print("No collection"); 
        } 
    });
tino.com
  • 1
  • 1
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) will help people understand the reasons for your code suggestion. – Gerhard Mar 22 '22 at 07:31