Name Firebase child as sequence array

倾然丶 夕夏残阳落幕 提交于 2020-01-24 18:48:25

问题


I want to use Fusionchart to read my Firebase data and create a chart in my web app. but my Firebase DB has a wrong structure, so the Fusionchart can't get data (my Firebase config is right).

Following is the code that I write data to Firebase, num is a value increased in each loop. But as shown in the attached picture, the child's name is not added as a sequence number. Another question is I don't want the unique key inside the child 1, just six various inside the child one is ok.

Any suggestions will be appreciated.

firebase.database().ref('testdata/User1').child(num).push({

 x: posX,

  y: posY,

MaxSpeed: maxSpeed, 

 steps: counter,

 time: Timeperiod /1000,

  speed: SpeedRecord,

  });

回答1:


If you don't want the push ID inside your pseudo-numeric keys, call set instead of push.

So:

firebase.database().ref('testdata/User1').child(num).set({
  x: posX,
  y: posY,
  MaxSpeed: maxSpeed, 
  steps: counter,
  time: Timeperiod /1000,
  speed: SpeedRecord,
});

Your other problems seems (it's impossible to be certain, since you didn't include the code for the increment) to come from the fact that num is a string. If that is indeed the case, increment it with:

num = String(parseInt(num) + 1);

Using such numeric keys is an antipattern in Firebase though, so I'd usually recommend against using them. If you must, at least pad them til a certain length, so that you can sort/filter on them easily.

Something as simple as:

num = String(parseInt(num) + 1).padLeft(5, "0");

Will work on all modern browsers, and ensures that all keys-that-look-like-numbers-but-behave-like-strings will show up in the order you expect.



来源:https://stackoverflow.com/questions/58049463/name-firebase-child-as-sequence-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!