Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling undefined Values with Firebase

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!

like image 440
Clay Banks Avatar asked Feb 18 '17 04:02

Clay Banks


2 Answers

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
  })
like image 126
gustavopch Avatar answered Nov 14 '22 06:11

gustavopch


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()

like image 10
Clay Banks Avatar answered Nov 14 '22 06:11

Clay Banks