我想向特定设备发送通知,所以我编写了此功能及其功能,但是用户名中未定义
日志输出:
获取此
after: { '-LhjfwZeu0Ryr6jYRq5r': { Price: '888', date: '2019-6-19', description: 'Ghh', id: 50, nameOfProblem: 'Vbh', providerName: 'Loy', providerService: 'Carpenter', statusInfo: 'Incomplete', time: '15:22', username:"devas" }}
username
是undefined
这是功能
exports.sendPushR = functions.database.ref('/request/{pid}/{uid}/orders')
.onWrite(async (snapshot, context) => {
const registrationTokens = "------";
const providerId = context.params.pid;
const userId = context.params.uid;
const event = context.params;
console.log("event", event);
console.log(`New Order from ${userId} to ${providerId}`);
const afterData = snapshot.after.val(); // data after the write
const username = snapshot.after.val().username;
console.log(afterData);
console.log(username);
const payload = {
notification: {
title: 'Message received',
body: `You received a new order from ${username} check it now! `,
sound: "default",
icon: "default",
}
};
try {
const response = await admin.messaging().sendToDevice(registrationTokens, payload);
console.log('Successfully sent message:', response);
}
catch (error) {
console.log('Error sending message:', error);
}
return null;
});
答案 0 :(得分:0)
由于要检索的对象具有生成的成员,因此可以使用for-in循环来检索值。
const object = snapshot.after.val()
for(const key in object) {
if (object.hasOwnProperty(key)) {
const element = object[key];
if(element.username) {
console.log(element.username);
break;
}
}
}
答案 1 :(得分:0)
当新订单添加到数据库中时,您编写的代码似乎可以运行。但是您已经声明要像这样触发:
exports.sendPushR = functions.database.ref('/request/{pid}/{uid}/orders')
.onWrite(async (snapshot, context) => {
这意味着,只要在用户的orders
节点下写入任何内容,该代码就会触发。要仅在该orders
节点下写入订单时触发,请将触发定义为:
exports.sendPushR = functions.database.ref('/request/{pid}/{uid}/orders/{orderid}')
.onWrite(async (snapshot, context) => {
上面的区别是该路径现在包含{orderid}
,这意味着它将触发树的下一级,而您的snapshot.after
将不再包含-L
级别。
由于您实际上似乎只在乎订单的创建时间,因此您也只能对此进行触发(这意味着在更新或删除订单时不会调用您的函数)。就像这样:
exports.sendPushR = functions.database.ref('/request/{pid}/{uid}/orders/{orderid}')
.onCreate(async (snapshot, context) => {
...
const afterData = snapshot.val();
const username = snapshot.val().username;
console.log(afterData);
console.log(username);
...
});
在这里,我们再次在JSON的较低级别上触发。但是由于现在我们触发了onCreate
,所以我们不再有前后快照,而只需执行snapshot.val()
即可获取刚刚创建的数据。