首页 > 解决方案 > 如何将使用“new”运算符创建的对象保存到 Firestore?

问题描述

我有一个简单的打字稿通知类,我正在尝试实例化并保存到 Firestore

 let notification = new Notification(
    new User(followerDoc.username, followerDoc.photoUrl)
  );
  _usersRef
    .doc(uid)
    .collection("notifications")
    .add(notification)

哪个抛出

错误:参数“data”的值不是有效的 Firestore 文档。无法序列化“用户”类型的对象(在“用户”字段中找到0)。Firestore 不支持具有自定义原型的 JavaScript 对象(即通过“new”运算符创建的对象)。

我可以手动展开对象并像这样保存它:

  _usersRef
    .doc(uid)
    .collection("notifications")
    .add({
      isRead: notification.isRead,
      users: [{username: notification.users[0].username, photoUrl: notification.users[0].photoUrl}],
      notNamedCount: notification.notNamedCount,
      type: "followers",
    })

但这比我想做的还要多。有没有办法将使用“new”运算符创建的对象保存到 firestore?

标签: javascriptgoogle-cloud-firestore

解决方案


不,这是不可能的。错误消息告诉您必须提供一个纯 JavaScript 对象,其键和值是您要在文档中创建的字段。Firestore SDK 不接受自定义对象。考虑改为在 Notification 对象上创建一个方法,将其转换为普通对象,就像您对任何具有toJSON方法的对象所期望的那样。


推荐阅读