Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Javascript / Typescript map compatibility

When I try to write a map to firebase I run into this error:

FirebaseError: Function DocumentReference.set() called with invalid data. Unsupported field value: a custom Map object (found in field documentData.elements)

I want to write maps instead of arrays to firebase to be able to merge datasets without overwriting the whole array but only adding or removing entries of the map. However, I can't get the map working, even if the firebase documentation says it's supporting maps.

My interface looks like this:

export interface Element {
   uid:string;
   value:string;
}
export interface DocumentData {
    uid: string;
    elements: Map<string, Element>;
}

Writing those as a document does not work and fails with the error above.

let documentData = {uid:"test_uid", elements: new Map([{"one", "test_string"}],[{"two", "test_string"}]]);
...
...
            .doc(documentData.uid)
            .set({documentData, {merge: true});

Does anybody have an idea how to write the map to the storage please? Is it actually an issue with the map or am I using set wrong?

like image 442
Solipsus Avatar asked Mar 14 '26 02:03

Solipsus


1 Answers

Firestore only accepts plain old JavaScript objects that contain the fields and values to write to the document. It doesn't accept an ES6 Map object, which is very much not the same thing.

Simply build the object and pass it to set():

const data = {
    uid: "test_uid",
    elements: {
        one: "test_string",
        two, "test_string"
    }
}

set(data, {merge: true})

I suggest consulting the documentation for more examples. Map objects are supported for Java, but not for JavaScript.

What will happen with the above code is it will update two fields, an "elements" will be a Firestore map type field.

like image 126
Doug Stevenson Avatar answered Mar 15 '26 16:03

Doug Stevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!