首先,我必须说我拥有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不是函数 at response.results.forEach(/user_code/index.js:127:36) at Array.forEach(native) 在admin.messaging.sendToDevice.then.response(/user_code/index.js:122:26) at process._tickDomainCallback(internal / process / next_tick.js:135:7)
原因是什么?
答案 0 :(得分: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));
}
});
}