skip to Main Content

I am currently working on a calorie-tracking app that uses Firestore.

I used Firestore to store food items in a document. However, some of these food items contain restricted characters (‘~’, ‘*’, ‘/’, ‘[‘, or ‘]’) that are not allowed in the field path.

For instance, this map that contains the food items. Note the use of the restricted character.

Is there a recommended way of handling the use of restricted characters? I’m thinking of encoding and decoding the strings before updating Firestore and decoding them when getting the documents, by replacing all restricted characters with specific strings.

Appreciate the help! Thank you!

2

Answers


  1. Encode:

    var encodeFirebaseKey = function(key) {
        return encodeURIComponent(key).replace(/./g, '%2E');
    };
    
    // Examples
    console.log(encodeFirebaseKey('[email protected]')); // "Henry%2EMorgan%40caribbean%2Esea"
    console.log(encodeFirebaseKey('02/10/2013')); // "02%2F10%2F2013"
    

    decode:

    var decodeFirebaseKey = function(encodedKey) {
        return decodeURIComponent(encodedKey.replace(/%2E/g, '.'));
    };
    
    // Examples
    console.log(decodeFirebaseKey('Henry%2EMorgan%40caribbean%2Esea')); // "[email protected]"
    console.log(decodeFirebaseKey('02%2F10%2F2013')); // "02/10/2013"
    
    Login or Signup to reply.
  2. Yes, that’s correct, when working with Firestore, there are certain characters like ('~', '*', '/', '[', or ']') which are not allowed to be used as keys in documents.

    Is there a recommended way of handling the use of restricted characters? I’m thinking of encoding and decoding the strings before updating Firestore and decoding them when getting the documents, by replacing all restricted characters with specific strings.

    While encoding and decoding the strings might solve the problem, there is another way of handling this situation. So instead of using those strings as keys you can add them as string values, where there are no restrictions. For instance, let’s assume you need to have a key called AC/DC, which obviously cannot be used as a key because it contains a forward slash /. So instead of using:

    $docId:
     |
     --- AC/DC: "Best Rock band"
    

    You can use a Map and store the info like this:

    $docId:
     |
     --- name: "AC/DC"
     |
     --- description: "Best Rock band"
    

    In this way, you also be able to map the the Firestore document into an object of type RockBand for example.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search