javascript - 如何将使用“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?
解决方案
不,这是不可能的。错误消息告诉您必须提供一个纯 JavaScript 对象,其键和值是您要在文档中创建的字段。Firestore SDK 不接受自定义对象。考虑改为在 Notification 对象上创建一个方法,将其转换为普通对象,就像您对任何具有toJSON方法的对象所期望的那样。
推荐阅读
- angular - 不同选项卡中的相同 Highchart 未加载 - 仅加载第一个选项卡
- c++ - 模板模板参数和函数调用
- thruk - Thruk - 模板 - 当主机是主机组的成员时添加 href
- php - 如何检查从用户获取的 PostgreSQL 日期时间格式字符串的有效性?
- typescript - 有没有办法在打字稿定义中引用函数参数?
- python - 惰性排序函数,timsort
- java - 无法部分比较空手道框架中的两个 Json
- xamarin - 如何在 Xamarin 中将 DPI 设备获取到 PCL。形式?
- java - 检查当前时间是否在 Java 中的给定时间和日期名称之间
- java - RedisCacheWriter 和 RedisTemplate 有什么区别