【发布时间】:2021-08-25 15:03:08
【问题描述】:
我正在尝试从集合(存储在 Firestore)中的文档中获取单个字段值。 (由触发的函数)调用以下函数来执行此查询并返回结果。
将查询结果提取到 helper_token 对象后 - 我无法访问其中的 DATA(字段)。
我尝试了很多东西,包括:
helper_token[0].device_token;
helper_token.data().device_token;
JSON.stringify(helper_token);
没有什么对我有用。 日志总是显示如下结果:
helper_token = {}
helper_token = undefined
我错过了什么? 如何根据user 获得device_token?
const admin = require('firebase-admin'); //required to access the FB RT DB
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
function getHelperToken(helperId) {
//Get token from Firestore
const tokensRef = db.collection('tokens');
const helper_token = tokensRef.where('user', '==', 'TM1EOV4lYlgEIly0cnGHVmCnybT2').get();
if (helper_token.empty) {
functions.logger.log('helper_token EMPTY');
}
functions.logger.log('helper_token=' + JSON.stringify(helper_token));
return helper_token.device_token;
};
为了完整起见,在此处将完整的调用函数添加到上述函数中:
//DB triggered function - upon writing a child in the HElpersInvitations reference
exports.sendHelperInvitation = functions.database.ref('/HelpersInvitations/{helper_invitation_id}')
.onCreate((snapshot, context) => {
const helperId = snapshot.val().helperId;
const title = snapshot.val().title;
const body = snapshot.val().body;
//Get the helper token by Id
functions.logger.log('HelperID=' + helperId);
functions.logger.log('getHelperToken=' + getHelperToken(helperId));
const helper_token2 = getHelperToken(helperId);
//Notification payload
const payload = {
notification: {
title: title,
body: body,
icon: 'default',
click_action: 'com.skillblaster.app.helperinvitationnotification'
}
}
// //Send the notification
functions.logger.log('helper_token [BEFORE sendToDevice]=' + helper_token2);
return admin.messaging().sendToDevice(helper_token2, payload);
});
【问题讨论】: