0

I have a firestore database with data like this:

enter image description here

Now, I access this data with doc('mydoc').get().data() and it returns the data. But, even without the data changing, if I make the same call again and again, I get different response. I mean, the data is the same, but the order of the fields is different each time.

Here's my logs with two calls, see how the field order is random? Not just between objects in the same request, but between the same object in different requests.

enter image description here

I'm accessing this data in a Cloud Function and serving it as an API endpoint. I want to cache the response if the data (in the database) hasn't changed, but I can't, because the data (as returned by doc.get().data()) is constantly changing.

From what I could find, this might stem from ProtoBuf encoding.

My question: is there any way to get a consistent response to a firebase query when the underlying data isn't changing?

And if no, is my only option to JSON.stringify() the whole object before putting it into firestore? (I don't need to query within document objects.)

Edit for clarity: I am not expecting to know in advance the order of the fields being returned. I am expecting (hoping) that the order will be the same each time.

David Gilbertson
  • 4,219
  • 1
  • 26
  • 32

1 Answers1

2

JSON object fields are unordered as per the JSON spec. Individual implementations of JSON are free to rearrange order however they see fit, and there's no surefire way to guarantee an order. See e.g. this answer.

This isn't a Firestore-specific problem, this is just generally how JSON objects work. You cannot and should not depend on the order of fields for any parsing or representation.

If display order is extremely important to you, you might want to investigate libraries like ordered-json.

Michael Bleigh
  • 25,334
  • 2
  • 79
  • 85
  • Thanks for the reply. ordered-json doesn't help. To be clear, I don't care what order the fields are in (and don't know in advance the shape of the object). I had just assumed that whatever order they did come back in would be the same each time. I did not expect that doing the same thing multiple times would result in different results. I'd be curious to know what drives the apparent randomness. – David Gilbertson Dec 13 '19 at 23:10
  • If serialization is the concern, [this question](https://stackoverflow.com/questions/16167581/sort-object-properties-and-json-stringify) might have some help for you. – Michael Bleigh Dec 17 '19 at 17:53