【问题标题】:Trying to save an array of objects to Firestore and load it back尝试将一组对象保存到 Firestore 并将其加载回来
【发布时间】:2021-05-01 22:14:05
【问题描述】:

如何将对象数组保存到 Firestore 并重新加载?我收到此错误

未捕获的 FirebaseError:调用函数 DocumentReference.set() 无效数据。不支持的字段值:自定义对象(在 记录用户书籍/图书馆)

这是我将其保存到 Firebase 并在对 myLibrary 数组进行修改后稍后加载的代码。

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

【问题讨论】:

标签: javascript firebase google-cloud-firestore


【解决方案1】:

您似乎正试图在文档中存储一个空数组,然后开始监听更新?

在它里面有数据之前,我不会存储空数组,或者将它与样板数据一起存储。

在您的代码中,您在向其添加对象之前调用了“saveLibrary()”。我认为这就是导致问题的原因。

我还鼓励您在 .set() 函数中使用 {merge:true},这样您就不会覆盖文档。 ref here

【讨论】:

    猜你喜欢
    • 2022-12-07
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 2022-01-22
    • 2013-07-13
    • 2015-09-26
    • 1970-01-01
    相关资源
    最近更新 更多