Firebase will not store keys with null values

I have an object like:

var _json = { "objects":[{ "type":"path", "originX":"center", "originY":"center", "left":48.59, "top":132.5, "width":64.5,"height":173, "fill":null,"stroke":"#3f7cc4", "strokeWidth":12,"strokeDashArray":null }]} 

I save this object using Firebase as:

 var myDataRef = new Firebase(<...>); myDataRef.child("saved_projects").child(authData.uid).update({'P3': _json}); 

But when I get the same with the Firebase on method and get the value as:

 snapshot.val() 

I get the object, but keys with null values ​​are removed, i.e. I got:

 {"objects":[ {"type":"path", "originX":"center", "originY":"center","left":48.59, "top":132.5,"width":64.5, "height":173, "stroke":"#3f7cc4","strokeWidth":12 }]} 

This causes me some weird problems, since I use Fabric.js , and this needs these values. Please, help!

EDIT / UPDATE (Hack)

I am currently using a weird HACK before storing an object in Firebase. I convert all null values ​​to 0 . But I want to know a better way to do it.

 function recursivelyReplaceNullToZero(j) { for (var i in j){ if (typeof j[i] === "object") { recursivelyReplaceNullToZero(j[i]); } if (j[i] === null) { j[i] = 0; } } } recursivelyReplaceNullToZero(_json); 
+7
javascript object firebase
source share
3 answers

I am currently using a weird HACK before I store an object in Firebase, I convert all the null values ​​to 0. But I want to know much better, please!

 function recursivelyReplaceNullToZero(j) { for (var i in j){ if (typeof j[i] === "object") { recursivelyReplaceNullToZero(j[i]); } if (j[i] === null) { j[i] = 0; } } } recursivelyReplaceNullToZero(_json); 
+2
source share

This is the expected behavior. AFAIK json systems work like this.

Instead, you should set zeros in your code for keys that are not in the database.
As an analogy: think about leading zeros - you do not write before the number.

0
source share

fill will be a string type, and they can be empty in Firestore. strokeDashArray would be an array types, and they may also contain an empty string (among other data types). See the image below, which is a screenshot of Firestore. You are right about null although it will not store properties with a null value.

Remember, however, that Firestore is a document database, and it does not contain a schema - this means that not every document should have all fields (semi-structured).

Thus, instead of storing useless properties, simply handle the possibility that the property may not be in your code, for example,

 if(doc.exists){ if(doc.data().fill){ // now you do what you want with the fill property } else { // there is no fill data } } 

enter image description here

0
source share

All Articles