Home > other >  How to create unique IDs inside map field?
How to create unique IDs inside map field?

Time:10-31

Data Structure

Countries (Collection)
|
--- 5nHsOxXPPenciyejILWP (Document)
    |
    --- Country Name (Map)
        |
        --- en (String) => Germany
        --- ar (String) => ألمانيا
        --- es (String) => Alemania
        --- it (String) => Germania
        --- de (String) => Deutschland
        --- ru (String) => Германия
    --- Cities (Map)
        |
        --- Berlin (String) => Berlin
        --- Munich (String) => Munich
        --- Frankfurt (String) => Frankfurt

Posts (Collection)
|
--- RhwFwkvSZ2WCh2K1O7xg (Document)
    |
    --- Title (String) => ...
    --- Description (String) => ...
    --- Country ID (String) => 5nHsOxXPPenciyejILWP
    --- City ID (String) => Berlin

In the Cities field, I want the keys to be unique IDs such as b4ejx8nUIFrXE0EkVrbs instead of using cities names.

I'm currently make it like this Berlin (String) => Berlin but I want it to be like this b4ejx8nUIFrXE0EkVrbs (String) => Berlin and in Posts collection it must be like this City ID (String) => b4ejx8nUIFrXE0EkVrbs instead of City ID (String) => Berlin.

I can solve the problem by creating a subcollection inside the Countries collection and every city in this situation will have a unique ID but this scenario will cost me a lot of reads instead of 1 read-only.

Is there any way to create a unique id that looks like this SKwFaGBYimiFBLUbZ9Oe, aXNTJsW6f6nTOsU7NBNO, EG1lo3Bbcnv9SJwLUGt5, q4QdEz3QPpvWu39gwpuK, etc... instead of cities names?

CodePudding user response:

You can always generate your own IDs and use them while adding the data. There are packages like UUID or you can even get those random IDs from Firebase SDK like this:

const randomId = firebase.firestore().collection('users').doc().id
// use this randomId while adding data
  • Related