DEV Community

Uday
Uday

Posted on

Saving unique data in firebase using sub-collection

In this post i will tell you how you can save unique data for each user which can be saved only once a day.

So i had this requirement where user wants to save their data but only once a day. If user tries to save the data again, they will get an error saying 'You can only save data once per day'. The meaning of doing this was so that we can get the average data of a week or a month and then display it as a graph for the user.

There are often user scenarios where you don't want to overwrite the data and need to set some business rule around how often the user can log the data or not.

The key is in the hierarchy of the data and how that is structured.

So let's say just for the sake of argument the user wants to log when they get to work in the morning and once this is logged, it should not be edited.

It is very easy, first of all you have to create a collection, say 'arrival'. Then you have to give its document id, in my case the document id is the uid of the current user who is logged in.

 _firestore
                        .collection('arrival')
                        .doc(_auth.currentUser.uid)
                        .collection('userarrival')
                        .doc(current1)
Enter fullscreen mode Exit fullscreen mode

in above code, _auth.currentUser.uid is giving me the unique id of each user as doc id. Then i have created a sub-collection named 'userarrival'. And then for its document-id i am giving the current date in the format(YYYY-MM-DD).

So whenever user enters data on a new day it will be added in the cloud firestore. For checking if data document already exists in the database, i am checking it with a method which returns a bool.

Future<bool> checkIfDocExists(id) async {
    try {
      var collectionRef = _firestore
          .collection('arrival')
          .doc(_auth.currentUser.uid)
          .collection('userarrival');
      var doc = await collectionRef.doc(id).get();
      return doc.exists;
    } catch (e) {
      throw e;
    }
  }
Enter fullscreen mode Exit fullscreen mode

So in the above code, i am giving id as current date in the format(YYYY-MM-DD), it will check if todays date document is already present or not. If exists, it will return true, else false.
and if document is present, it will give an error using showDialog() in flutter. Else, add the data in the database.

_firestore
                        .collection('arrival')
                        .doc(_auth.currentUser.uid)
                        .collection('userarrival')
                        .doc(current1)
                        .set({
                      //data
                    });
                    Navigator.pop(context);
                    print('pain value saved in db');
                  }
Enter fullscreen mode Exit fullscreen mode

Thats, it. Thats all you have to do to save unique user data for each day.

Top comments (0)