简体   繁体   中英

Firebase database keys beginning with underscore removed

I started writing a web app and the user object has a _username key so its on the beginning.

If I add the object to firebase database it is not there - everything else is.

Why is this key/value pair not in the database? I mean it is valid JSON, isn't it?
I mean are there other solutions than simply renaming it?

my object which is pushed to an array has following structure:

{
    _username:"",
    history:[],
    // ...
}

My code:

var users = $firebaseArray(ref.child("user"));

// adding user
users.$add($scope.session.user);
// logging afterwards - also no '_username'

// logging on init
users.$loaded().then(function (data) {
    $log.debug(data);
});

Everything is stored, except the underline var...

It looks like $add() (or more specifically $firebaseUtils.toJSON() ) drop properties whose name starts with an _ . A quick way to see this is:

console.log($firebaseUtils.toJSON(user));

A workaround would be to directly write the user object to the database through the JavaScript SDK:

ref.child("user").push(user);

This does write all properties with valid key names, including the ones prefixed with a _ .

Since AngularFire is built on top of the same JavaScript SDK, it will pick up the changes straight away.

Demo in jsbin: http://jsbin.com/lobadej/edit?js,console

This was a design decision, based on the fact that a common JavaScript convention for declaring private variables is to prefix them with _ .

For context on why it's different than the default SDK behavior, keep in mind that AngularFire is creating class instances that can be extended, and provide client-side functionality (not just raw JSON objects for data transfer). So our goal here is to make it as simple and straightforward as possible to extend and use $firebaseArray and $firebaseObject, and to make saving and server sync as transparent as possible.

To do so, you need a simple convention to separate "local" or private things from ones you want sent to the server. Since $ is technically reserved by the Angular libs, _ continues to be the appropriate way to prefix your private variables and methods pre-ES6.

We could revisit if there were significant numbers of people having issues here, but given that it's been implemented this way nearly 3 years and this is the first comment on it, I suspect it's fine as is.

See also: https://github.com/firebase/angularfire/issues/901

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM