skip to Main Content

Given an unknown JavaScript value, I would like to write it to a property of a Firestore document. But Firestore rejects some values. For example when trying to store the browser’s window object, Firestore reports an error:

#object[FirebaseError FirebaseError: [code=invalid-argument]: Function DocumentReference.update() called with invalid data.
Unsupported field value: a custom Window object (found in field data.window in document errors/Ic0sCeKezM1x1kDBI3Hy1)]

The usecase ist to write catched errors to Firestore. But catched errors can be or can contain all kinds of (nested) properties.

So how can I "prepare" an arbitrary value for storage in Firebase? Invalid values could be converted to Strings or just skipped from writing. But the coercion must always succeed.

2

Answers


  1. Chosen as BEST ANSWER

    Pass arbitrary objects through json-prune (https://www.npmjs.com/package/json-prune) before storing them in Firestore.


  2. While Firestore is schemaless, the list of types you can store in it is quite well defined. As you’ve found, arbitrary objects may not meet these requirements – especially not when they contain methods.

    I found it best to not accept arbitrary objects, but actually be explicit about the type of each object I store in Firestore. So for example with a TypeScript definition for each object.

    The simplest I found to coerce arbitrary JavaScript objects into Firestore compatible data is by converting them to JSON and back with:

    const firestoreData = JSON.parse(JSON.stringify(arbitraryObject));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search