I have this database in Firebase:
touristSpots {
1stSpot : {
key: value,
...
nearSpots: {
3 : {
somekey: somevalue
}
5 : {
somekey2: somevalue2
}
}
},
2ndSpot : {
key : value,
...
nearSpots: {
2 : {
somekey3: somevalue3
},
4 : {
somekey4: somevalue4
},
}
}
}
Thus, I am expecting a response to be same as mentioned. But Firebase reponse is something like:
touristSpots {
1stSpot : {
key: value
...
nearSpots[
null, {
somekey: somevalue
},
null, {
somekey2: somevalue2
}
]
}
2ndSpot : {
key : value
...
nearSpots: {
2 : {
somekey3: somevalue3
}
4 : {
somekey4: somevalue4
}
}
}
}
As you can see the nearSpot on 1st record became an array [] and the second one became an Object {}. I can deal with each one of them but having mixed results like this then the program cannot convert them to an object due to converting an [] instead of an object.
I am new on firebase and am aware that C# has very limited support. I also cannot seem to find a workaround on this one. Have anybody else experienced this? Thank you
CodePudding user response:
You're using sequential, numeric keys in the database, which means the SDKs and REST API assume that you're storing an array. When you retrieve a subset of the items of such a structure, you may end up with an array with null
elements in there:
nearSpots[
null, // index 0: no item, so null value
{ somekey: somevalue }, // index 1
null, // index 2: no item, so null value
{ somekey2: somevalue2 } // index 3
]
Using arrays in Firebase is typically considered an anti-pattern, and is discouraged in this classic blog post: Best Practices: Arrays in Firebase.
The easiest workaround is to use keys with a short prefix, such as key0
, key1
, etc. This prevents the Firebase SDK/API from coercing the result into an array.