【发布时间】:2019-05-25 00:30:15
【问题描述】:
我正在尝试让 Google firebase 云函数 codelab (https://codelabs.developers.google.com/codelabs/firebase-cloud-functions/#9) 与 Firestore 一起工作(现在它为实时数据库配置)。
我在修改 Firestore 的原始代码时遇到问题:
// Sends a notifications to all users when a new message is posted.
exports.sendNotifications = functions.database.ref('/messages/{messageId}').onCreate(
async (snapshot) => {
// Notification details.
const text = snapshot.val().text;
const payload = {
}
};
// Get the list of device tokens.
const allTokens = await admin.database().ref('fcmTokens').once('value');
if (allTokens.exists()) {
// Listing all device tokens to send a notification to.
const tokens = Object.keys(allTokens.val());
// Send notifications to all tokens.
const response = await admin.messaging().sendToDevice(tokens, payload);
}
});
到目前为止我已经做了:
// Sends a notifications to all users when a new message is posted.
exports.sendNotifications = functions.firestore.document(‘/userscollection/{uid}').onCreate(
async (snapshot) => {
// Notification details.
const text = snapshot.val().text;
const payload = {
notification: {
}
};
// Get the list of device tokens.
const allTokens = await admin.firestore().collection('users').where('FCMToken', '>', "").get()
.then(snap =>{
if (snap.empty) {
console.log('snap is empty');
return;
}
snap.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
})
.catch(err => {
console.log('Error getting docs', err);
});
console.log('allTokens is: ', allTokens);
if (allTokens.exists()) {
// Listing all device tokens to send a notification to.
const tokens = Object.keys(allTokens.val());
// Send notifications to all tokens.
const response = await admin.messaging().sendToDevice(tokens, payload);
}
});
这个听/userscollection根集合正确所以触发云功能。但是控制台中的函数返回错误:TypeError: Cannot read property 'exists' of undefined at Object.<anonymous>
还有
console.log('allTokens is: ', allTokens);
返回
allTokens is: undefined
在 Firestore 中,我将令牌存储在 /users 根集合中的用户文档中。所以我需要修改 codelab 以在 /users 集合中的所有用户文档中仅获取“token”字段。
有人帮忙吗? 谢谢!
【问题讨论】:
标签: node.js typescript firebase google-cloud-firestore google-cloud-functions