I have a simple form in my web application that persists a JSON object to my Firebase database. Not every field on this form is required, so when the object being sent is constructed, it may have several undefined
properties.
Being that Firebase throws an error when trying to persist undefined
values, (not to mention, you should not have an undefined
value on a JSON object), I'm wondering if there's any method provided by the framework to override all undefined values to null
or even an empty string; I've yet to find a solution online.
Worst case scenario I could set all undefined properties to null
manually but I'd rather not do that
Any ideas or suggestions on this?
Thanks much!
For those using Firestore, it's now possible to ignore undefined
fields: https://github.com/googleapis/nodejs-firestore/issues/1031#issuecomment-636308604
elmasry: As of today May 29, 2020, Firebase Added support for calling FirebaseFiresore.settings with { ignoreUndefinedProperties: true }. When this parameter is set, Cloud Firestore ignores undefined properties inside objects rather than rejecting the API call.
Example:
firebase.firestore().settings({
ignoreUndefinedProperties: true,
})
await firebase
.firestore()
.collection('products')
.doc(productId)
.update({
name: undefined, // Won't throw an error
})
My solution was to simply stringify()
the object combined with a replacer
to replace all undefined values
obj = JSON.parse(JSON.stringify(obj, function(k, v) {
if (v === undefined) { return null; } return v;
}));
Then I convert it back to an object with JSON parse()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With