Adding a Dynamic Child to my Firebase Reference UR

2020-07-25 06:34发布

问题:

I've been attempting to dynamically add a child to my firebase data reference URL, so far with no luck.

Assume I have the following data structure:

MyApp
|-beta_signups
|-users
|--fred
|----email "fred@test.com"

I would like to be able to add people who sign up, as a child based on their email address under the "signups" section. here is what I tried, but it didn't work.

var myDataRef = new Firebase("https://myapp.firebaseio.com/beta_signups/");
  $('#submit').click(function() {
      var email = $('#email').val();
      myDataRef.child(email).push({email: email, beta_key: false});
      $('#email').val('We got it.');
  });

Any suggestions on how I can dynamically add the child?

回答1:

You can't use an email address as the key for a child path because it contains invalid characters. See Creating References in the docs.

You are also creating a child based on the email address, and then creating a child of the email by using push. Probably, you should just get rid of the .child(email) bit and use push to create the records.

var user_id = myDataRef.push({email: email, beta_key: false}).name();

The first thing to ask is whether you actually want to store the users by email. Generally, an ID is going to be much more useful (they may change their email later, in which case you have to go re-key all their user data in the system).

If that's a requirement, then you're either going to have to hash them or sanitize them. For example:

// replace all forbidden characters with something that won't appear in the email address
var key = email.replace(/[.$\[\]\/#]/, ','/);
myDataRef.child(key).set({email: email, beta_key: false});


标签: firebase