我正在努力向用户发送动态通知。因此,我正在处理Firebase Cloud Functions。 这是我的问题:如何在云功能端访问数据库?
这是我的代码:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
admin.initializeApp(functions.config().functions);
var newData;
//exports.myTrigger= functions.firestore.document().
exports.notificationTrigger = functions.firestore.document(`notifications/{notificationId}`).onCreate(async (snapshot, context) => {
if (snapshot.empty) {
console.log('No Devices');
return;
}
var notificationData = snapshot.data();
// notificationData.email;
console.log(`Data is : ${notificationData.email}`);
admin.database().ref(`users/${notificationData.email}/deviceToken`).then((snapshot) => {
var token = snapshot.data();
console.log('token',token)
return 1;
}).catch(err => {
console.error(err);
});
var tokens = [
`${token.deviceToken}`
];
var payload = {
notification: {
title: `Yeni Eklenen Değerin Maili : ${notificationData.email}`,
body: 'hüsen',
sound: 'default',
},
data: {
click_action: 'FLUTTER_NOTIFICATION_CLICK',
Messages:'Baba Mesajı from otomatik fonksiyon'
},
};
try {
const response = await admin.messaging().sendToDevice(tokens, payload);
console.log('Notification sent successfully');
} catch (err) {
console.log(err);
}
});
如您所见,首先,我想从 nofications 收集中获取电子邮件,然后使用该电子邮件,我想搜索使用该电子邮件的用户,之后,我想获取用户 deviceToken。
我尝试了很多关于语法的东西,但我没有得到任何结果:/
同样,我犯了某种错误:
在这里你可以看到错误:
- Reference.child 失败:第一个参数是无效路径 ="users/patientaccount@gmail.com/deviceToken"。路径必须是非空字符串,并且不能包含"."、"#"、"$"、"["或"]" at validatePathString (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:1667:15( at validateRootPathString (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:1679:5( at Reference.child (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:13843:17( at Database.ref (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:15097:48( at exports.notificationTrigger.functions.firestore.document.onCreate (/srv/index.js:37:24( at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23( at/worker/worker.js:825:24 在 在process._tickDomainCallback(内部/进程/next_tick.js:229:7(
错误消息告诉您出了什么问题:
Reference.child 失败:第一个参数是无效路径 ="users/patientaccount@gmail.com/deviceToken"。路径必须是非空字符串,并且不能包含"."、"#"、"$"、"["或"]">
包含电子邮件地址的路径具有无效字符.
。
如果要存储每用户数据,则应改用用户帐户的唯一 ID。 由于各种原因,电子邮件地址不能成为非常好的唯一标识符。