f-miyu / Plugin.CloudFirestore

MIT License
121 stars 44 forks source link

How to get the auto generated FirebaseID #12

Open ElishaMisoi opened 4 years ago

ElishaMisoi commented 4 years ago

How do I get the randomly generated ID when creating a document with auto generated id?

Or rather, is there a way to generate the random id manually before adding or setting a document?

ElishaMisoi commented 4 years ago

The method below seems to work. But surely, I bet there should be a better way of doing it.

Screenshot 2019-07-30 at 05 17 03
ElishaMisoi commented 4 years ago

Maybe a helper function for generating random FirebaseIDs

Screenshot 2019-07-30 at 05 31 37
AntvissMedia commented 4 years ago

Or give the document a set ID to begin with which you can track. The method below generates an ID of x characters (10 by default but can be set with passing the COUNT field:

public static string GenerateID (int count = -1)
        {
            Random random = new Random();
            int amount = 10;
            if (count > 0)
            {
                amount = count;
            }
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            return new string(Enumerable.Repeat(chars, amount)
              .Select(s => s[random.Next(s.Length)]).ToArray());
        }

Then pass this ID to firestore:

string docID = GenerateID (20);
CrossCloudFirestore.Current.Instance
                .GetCollection("MY_COLLECTION")
                .GetDocument(docID)
                .SetDataAsync(object);