猿问

云功能中未定义的用户名?

我想向特定设备发送通知,所以我编写了此函数及其工作正常,但我在用户名中未定义


日志输出:


得到这个


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;

    });


泛舟湖上清波郎朗
浏览 192回答 2
2回答

qq_遁去的一_1

看起来您编写的代码旨在在将新订单添加到数据库时运行。但是你已经声明它像这样触发: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 中的较低级别上触发。但是由于我们现在 trigger onCreate,我们不再有前后快照,而是只是snapshot.val()为了获取刚刚创建的数据。

哔哔one

由于您正在检索的对象具有生成的成员,您可以使用 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;        }      }}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答