0

How do I save an array of objects to Firestore and load it back? I get this error

Uncaught FirebaseError: Function DocumentReference.set() called with invalid data. Unsupported field value: a custom object (found in document userBooks/library)

This is my code to save it to Firebase and to load it later on after modifications have been done to myLibrary array.

let myLibrary = [];
let firestore = firebase.firestore();

let docRef = firestore.doc("userBooks/library");
saveLibrary = function () {
  docRef
    .set({
      userLibrary: myLibrary,
    })
    .then(function () {
      console.log("Library saved!");
    })
    .catch(function (error) {
      console.log("Got an error: ", error);
    });
};
saveLibrary()
getUpdate = function () {
  docRef.onSnapshot(function (doc) {
    if (doc && doc.exists) {
      const myData = doc.data();
      myLibrary = myData.userLibrary;
      console.log(myData.userLibrary);
    }
  });
};

// Here I add multiple objects to the array myLibrary.

saveLibrary();
getUpdate();
captaincustard
  • 321
  • 2
  • 12
  • Does this answer your question? [Function DocumentReference.set() called with invalid data. Unsupported field value: a custom Budget object](https://stackoverflow.com/questions/48156234/function-documentreference-set-called-with-invalid-data-unsupported-field-val) – Aziz Sonawalla Jan 28 '21 at 02:17

1 Answers1

1

It looks like you're trying to store an empty array inside the document, then start to listen to updates?

I wouldn't store the empty array until it has data inside it, or store it with boilerplate data.

In your code, you're calling " saveLibrary() " before adding objects to it. I think that's what's causing the issue.

I would also encourage you to use {merge:true} within your .set() functions, so you don't overwrite your documents. ref here