【问题标题】:Changing the notification field "seen" boolean in firebase to true via a transaction operation通过事务操作将firebase中的通知字段“seen”布尔值更改为true
【发布时间】:2021-05-19 02:54:32
【问题描述】:

我已经设置了一个 onClick 事件来调用一个函数,该函数将通过 firebase 将通知文档的“seen”字段更改为 true。当我尝试调用该函数时,我收到一条错误消息:

事务失败:TypeError:无法读取属性“_delegate”的 不明确的 在 qa (prebuilt-3c03a633-33a12d73.js:16242) 在 e.get (prebuilt-3c03a633-33a12d73.js:16336) 在 t.get (prebuilt-3c03a633-33a12d73.js:17913) 在 Header.js:64

*请注意:'_delegate' 的属性在预构建文件的函数中找到,但错误是 Header.js 的第 64 行发生的雪球效应,如下所示。问题出在“markNotificationsAsSeen”函数中。

给出的建议可能是将其从事务操作更改为批量写入操作,但我不确定。我在下面包含了我的代码:

    const markNotificationsAsSeen = () => {
        var notificationDocRef = db
            .collection("notifications")
            .doc("Ddo1Z3GtgwzytZig1GPD");

        return db
            .runTransaction((transaction) => {
                return transaction.get(notificationDocRef).then((notificationDoc) => {
                    if (!notificationDoc.exists) {
                        throw "Document does not exist!";
                    }

                    const doc = notificationDoc.get();
                    if (
                        doc.user.askerUserId === auth.currentUser.uid &&
                        doc.seen === false
                    ) {
                        console.log("I passed");
                    }
                    // transaction.update(notificationDocRef, { seen: false });
                });
            })
            .then(() => {
                console.log("Transaction successfully committed!");
            })
            .catch((error) => {
                console.log("Transaction failed: ", error);
            });
    };

【问题讨论】:

  • 无论您试图从中读取_delegate 的对象是未定义的,但是,_delegate 不在您的代码中。请发布错误的代码。
  • 需要查看错误对应的行号,希望也是。告诉我们过程,例如。 A -> B -> C -> D. 一切都从 handleQuestion 开始?还是?
  • 我已经用错误中的更多细节更新了问题。让我知道这是否可以澄清事情
  • 您将需要努力制作更简洁的问题/帖子以获得体面的答案。您发布的代码比将问题缩小到特定问题所需的代码多得多。请参阅how to write a good question 以获取有关获得可靠答案而不被误导的建议。

标签: javascript reactjs firebase google-cloud-firestore


【解决方案1】:

基本上,调用条件的唯一方法是使用 .get() 和 .then() 来调用查询快照。

这是一个链接,以防其他人遇到此问题:https://firebase.google.com/docs/firestore/query-data/queries

我可以使用以下代码解决它:

const markNotificationsAsSeen = () => {
    var notificationDocRef = db
        .collection("notifications")
        .where("user.askerUserId", "==", auth.currentUser.uid)
        .where("seen", "==", false)
        .get()
        .then((querySnapshot) => {
            querySnapshot.forEach((doc) => {
                for (const doc of querySnapshot.docs) {
                    doc.ref.update({ seen: true });
                }
                console.log(doc.id, " => ", doc.data());
            });
        })
        .catch((error) => {
            console.log("Error getting documents: ", error);
        });
};

【讨论】:

    猜你喜欢
    • 2023-01-27
    • 2021-06-05
    • 1970-01-01
    • 2015-07-11
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多