0

I am simply trying to store some data in my firebase realtime database, but when doing so I keep getting this error:

Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"

The problem isn’t the data I want to store, but the name I want to give the path. I want the path-name to be an URL. But it obviously contains those "illegal" symbols.

This is how I try to name the path and store some data:

// URL example: 
var newNote = firebase
  .database()
  .ref()
  .child("/https://developer.mozilla.org/en
 US/docs/Learn/JavaScript/First_steps/Strings") // <-- this is the problem
  .set({
    title: title,
    icon: icon,
    body: body,
    url: url,
  });

Any ideas on how to solve this?

Nick
  • 219
  • 4
  • 15

1 Answers1

0

You'll need to encode the URL so that it no longer contains any illegal characters. Since you also store the URL inside the node, you can get away with a one-way encoding for the key.

So for example, you could remove all illegal characters from the string. Assuming you don't want the database to interpret the / in the key, you'd also remove those, and end up with:

.child("/httpsdevelopermozillaorgen USdocsLearnJavaScriptFirst_stepsStrings")

Now whenever you get a URL in your code again, you apply the same encoding and end up with the same key.

There are many such encoding schemes, and you should pick what fits best for your use-case. For example, you could also replace the illegal characters with something, to result in a more readable key:

.child("/https___developer_mozilla_org_en US_docs_Learn_JavaScript_First_steps_Strings")

Or you could completely forego readability, and use a hash of the URL as its key:

.child(hashCode("/https://developer.mozilla.org/en US/docs/Learn/JavaScript/First_steps/Strings"))

Which would (with the hashCode function I linked) end up storing in:

.child("-1097737053")
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807