我将以下FCM推送通知推送到了Firebase函数:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();
exports.newSubscriberNotification = functions.firestore
.document('messages/{id}')
.onUpdate(async event => {
const data = event.after.data();
const content = data ? data.content : '';
const toUserId = data ? data.toUserId : '';
const payload = {
notification: {
title: 'New message',
body: `${content}`
}
};
const db = admin.firestore();
const devicesRef = db.collection('devices').where('userId', '==', toUserId);
const devices = await devicesRef.get();
const tokens: any = [];
devices.forEach(result => {
const token = result.data().token;
tokens.push(token);
});
return admin.messaging().sendToDevice(tokens, payload);
});
在我使用.onUpdate的代码中,我假设应该在消息集合之一更新时触发。这是一个消息传递应用程序,因此,无论何时更新消息传递集合,我都想向接收用户触发推送通知。
我获取了tuUserId,并使用它从devices集合中获取了该用户的设备令牌。我现在正在测试,因此toUserId与fromuserId相同,因为它只是在使用我的设备...因此希望当我更新message.doc()时,它将发送推送通知。
这是firebase中的邮件集合:
这是功能错误日志:
11:04:22.937 PM
newSubscriberNotification
Function execution started
11:04:22.946 PM
newSubscriberNotification
Error: Value for argument "value" is not a valid query constraint. Cannot use "undefined" as a Firestore value.
at Object.validateUserInput (/srv/node_modules/@google-cloud/firestore/build/src/serializer.js:273:15)
at validateQueryValue (/srv/node_modules/@google-cloud/firestore/build/src/reference.js:1844:18)
at CollectionReference.where (/srv/node_modules/@google-cloud/firestore/build/src/reference.js:956:9)
at exports.newSubscriberNotification.functions.firestore.document.onUpdate (/srv/lib/index.js:19:49)
at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23)
at /worker/worker.js:825:24
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
11:04:22.957 PM
newSubscriberNotification
Function execution took 21 ms, finished with status: 'error'
我很确定由于这个错误,它不喜欢我的.where子句: 在CollectionReference.where(/srv/node_modules/@google-cloud/firestore/build/src/reference.js:956:9)
我不确定为什么
答案 0 :(得分:1)
屏幕快照中的文档包含对象的数组,您的代码无法处理这些对象。您正在尝试从文档的根目录(不存在的地方)读取toUserId
。这意味着您的toUserId
的值为undefined
,Firestore会抱怨这一点。
在单个文档中看到多个对象/消息有点不寻常,因此您必须确定这是否真的是最好的方法。但是,如果是这样,则必须确定要将通知发送到这些对象中的哪个。如果要发送给所有这些对象,则可以遍历它们:
exports.newSubscriberNotification = functions.firestore
.document('messages/{id}')
.onUpdate(async event => {
const allMessages = event.after.data();
const db = admin.firestore();
Object.keys(allMessages).forEach((index) => {
let data = allMessages[index];
const content = data ? data.content : '';
const toUserId = data ? data.toUserId : '';
const payload = {
notification: {
title: 'New message',
body: `${content}`
}
};
const devicesRef = db.collection('devices').where('userId', '==', toUserId);
const devices = await devicesRef.get();
...
})
});