Home > database >  How to add number as firebase realtime database child without converting to array?
How to add number as firebase realtime database child without converting to array?

Time:03-24

I want to make a db structure like the following,

Example

But it just converts the whole object to an array,

Here's what I get when I export this json,

[ null, {
  "oPNfOlBcS4gl3rvZ4CIme9MDk0p1" : {
    "added_at" : 1647966583316,
    "city" : "Test",
    "country" : "Test",
    "name" : "Test",
    "state" : "Test",
    "uid" : "oPNfOlBcS4gl3rvZ4CIme9MDk0p1"
  }
}, {
  "oPNfOlBcS4gl3rvZ4CIme9MDk0p1" : {
    "added_at" : 1647966583316,
    "city" : "Test",
    "country" : "Test",
    "name" : "Test",
    "state" : "Test",
    "uid" : "oPNfOlBcS4gl3rvZ4CIme9MDk0p1"
  }
} ]

I tried keeping the first child as 1 and the second as "first" (or some random string) and exported json and here's what I got...

{
  "1" : {
    "oPNfOlBcS4gl3rvZ4CIme9MDk0p1" : {
      "added_at" : 1647966583316,
      "city" : "Test",
      "country" : "Test",
      "name" : "Test",
      "state" : "Test",
      "uid" : "oPNfOlBcS4gl3rvZ4CIme9MDk0p1"
    }
  },
  "first" : {
    "oPNfOlBcS4gl3rvZ4CIme9MDk0p1" : {
      "added_at" : 1647966583316,
      "city" : "Test",
      "country" : "Test",
      "name" : "Test",
      "state" : "Test",
      "uid" : "oPNfOlBcS4gl3rvZ4CIme9MDk0p1"
    }
  }
}

I want something similar, but with children like "1", "2" instead.

Is it possible? Or using children like "first", "second" is the only solution right now?

CodePudding user response:

When you read a node with sequential numeric keys (as in your screenshot and first JSON example), the Firebase SDK (and REST) API) automatically coerce that data to an array. There is no way to configure this behavior.

If you don't want the array coercion you should use non-numeric keys. My common approach is to prefix each key with a short string, like "key1", "key2", etc.

Also see: Best Practices: Arrays in Firebase.

  • Related