Firestore函数:处理映射值

问题描述 投票:1回答:1

首先,我必须说我拥有Java的中级经验,而且非常基本的JS。

我正在尝试从我的数据库中删除过期的令牌,以实现我的目的:

function sendNotificationToUser(payload, userSnapshot) {
    const userId = userSnapshot.id;
    const user = userSnapshot.data();
    let tokenMap = user.tokens;
    const tokens = Object.keys(tokenMap);

    const options = {priority: "high"};
    admin.messaging().sendToDevice(tokens, payload, options).then(response => {
        // For each message check if there was an error.
        response.results.forEach((result, index) => {
            const error = result.error;
            if (error) {
                // Cleanup the tokens who are not registered anymore.
                if (error.code === 'messaging/invalid-registration-token' || error.code === 'messaging/registration-token-not-registered') {
                    tokenMap.delete(tokens[index]);
                }
            } else{
                console.log("Sent to user: ", user.name, " " ,user.surname, " notification: ", payload, " tokens: ", tokens[index]);
            }
        });

        usersRef.doc(userId).update({
            tokens: tokenMap
        });
    });
}

获取tokenMap的密钥没问题,但看起来我无法删除带有.delete()的条目,因为我在我的日志中得到了:

TypeError:tokenMap.delete不是在admin.messaging.sendToDevice.then.response(/ user_code / index)的Array.forEach(native)的response.results.forEach(/user_code/index.js:127:36)处的函数。 js:122:26)at process._tickDomainCallback(internal / process / next_tick.js:135:7)

是什么原因??

node.js hashmap google-cloud-functions google-cloud-firestore
1个回答
1
投票

解决了:

delete tokensObj[tokensArray[index]];

完整代码:

function sendNotificationToUser(payload, userSnapshot) {
const user = userSnapshot.data();
let tokensObj = user.tokens;
const tokensArray = Object.keys(tokensObj);

let toUpdate = false;

const options = {priority: "high"};
admin.messaging().sendToDevice(tokensArray, payload, options).then(response => {
    // For each message check if there was an error.
    response.results.forEach((result, index) => {
        const error = result.error;
        if (error) {
            // Cleanup the tokens who are not registered anymore.
            if (error.code === 'messaging/invalid-registration-token' || error.code === 'messaging/registration-token-not-registered') {
                toUpdate = true;
                delete tokensObj[tokensArray[index]];
            }
        } else {
            console.log("Sent to user: ", user.name, " ", user.surname, " notification: ", payload, " token: ", tokensArray[index]);
        }
    });

    if (toUpdate === true) {
        userSnapshot.ref.update({ tokens: tokensObj }).catch(error => console.log(error));
    }
});

}

© www.soinside.com 2019 - 2024. All rights reserved.