首页 > 解决方案 > 如何读取/更新从 Firebase 转换为 JSON 的对象实例

问题描述

我目前陷入在firebase中检索存储为JSON的类的过程中(我将对象的每个实例转换为JSON并存储它)。我的主要目标是使用 Cloud Functions 中的 nodejs 读取存储在 Firestore 中的 JSON 对象 () 中的一段数据(在会议上也是一个 JSON 对象)meeting,因为我正在尝试使用 FCM 创建推送通知。

我的代码:


    exports.meetingsUpdate = functions.firestore.document('/meetings/{meetingId}')
        .onWrite(async (snap,context) => {
            var data = snap.after.data()
            data = await data.meeting;
            const obj = await data.meeting;
            const uids = await obj.groupUID;
            const requestor = await obj.requesterName;
            const payload = {
            notification: {
                title: 'Meeting request',
                body: 'You have a meeting request from ' + requestor
            }
        }
        for (uid of uids) {
            // eslint-disable-next-line no-await-in-loop
            const doc = await admin.firestore()
                        .collection('userNotificationTokens')
                        .doc(uid)
                        .get()
            // eslint-disable-next-line no-await-in-loop
            const token = await doc.data().token
            // eslint-disable-next-line no-await-in-loop
            const response = await admin.messaging().sendToDevice(token, payload)
            .then((res) => {
                console.log("Message sent successfully!", res.body) 
            });
        }
        return null;
    

        })

这是我的数据库映射的样子带有代表 JSON 对象的“会议”属性

我对 Firebase 及其功能相对较新,并且一直遇到错误,例如

SyntaxError:位置 0 处 JSON 中的意外标记 u

TypeError:无法读取未定义的属性“groupUID”

TypeError:无法读取未定义的属性“令牌”

尽管尝试了各种方法和调整,但已经有一段时间了。

第一个会议值是一个 JSON 对象,第二个会议属性也是一个 JSON 对象。为有些复杂的数据存储道歉。

标签: javascriptnode.jsfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


推荐阅读