[英]Firebase functions: getting document data inside a function
im making a type of chat app.我正在制作一种聊天应用程序。 Im trying to write a firestore function that listens to a specific document that, when updated, will trigger the function to send a push notification to a specific user.
我正在尝试编写一个 Firestore function 来侦听特定文档,该文档在更新时将触发 function 向特定用户发送推送通知。 However, im receiving an error.
但是,我收到一个错误。 So far, i have:
到目前为止,我有:
export const messageListener = functions.firestore
.document("stingrayMessageListener/stingrayMessageListener")
.onWrite(async (change) => {
const beforeData = change?.before?.data();
const afterData = change?.before?.data();
if (beforeData?.receiverId!=afterData?.receiverId) {
const docRef = admin.firestore().doc("users/${afterData?.receiverId}");
const docSnap = await docRef.get();
const payload = {
notification: {
title: "New message!",
body: "${afterData?.senderName} has sent you a message!",
},
data: {
body: "message",
},
};
admin.messaging().sendToDevice(docSnap.data()?.token, payload);
}
});
This function is spitting out the following error:这个 function 吐出以下错误:
Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array
提供给 sendToDevice() 的注册令牌必须是非空字符串或非空数组
Im pretty sure this is implying that docSnap() is returning as null, because token is a field on all user documents.我很确定这意味着 docSnap() 以 null 的形式返回,因为令牌是所有用户文档上的一个字段。 Am I doing something wrong?
难道我做错了什么?
In addition to using template literals in your document paths as you answered, both beforeData
and afterData
are assigned to change?.before?.data()
, meaning your function won't send notifications to any device:除了在您回答时在文档路径中使用模板文字外,
beforeData
和afterData
都被分配为change?.before?.data()
,这意味着您的 function 不会向任何设备发送通知:
const beforeData = change?.before?.data();
const afterData = change?.before?.data();
if (beforeData?.receiverId != afterData?.receiverId) {
//above condition won't be true
...
You'd only need to use the after property which holds the changed document.您只需要使用保存更改后的文档的after属性。
const afterData = change?.after?.data();
Let me know if this was helpful.让我知道这是否有帮助。
So, turns out it was a very simple solution.所以,事实证明这是一个非常简单的解决方案。 In Typescript, you can dont use "" to use a variable in a string.
在 Typescript 中,不能使用 "" 来使用字符串中的变量。 You use ``.
你用```。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.