如何在节点js中获取token_id?
数据库图片
Index.js代码在下面,通过此代码,它提供了存储在user_id中的所有数据,但我无法仅获得{token_id}的特定字段。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var db = admin.firestore();
exports.sendoNotification = functions.firestore.document('/Users/{user_id}/Notification/{notification_id}').onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification from : ', user_id);
var cityRef = db.collection('Users').doc(user_id);
var getDoc = cityRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());
}
})
.catch(err => {
console.log('Error getting document', err);
return Promise.all([getDoc]).then(result => {
const tokenId = result[0].data().token_id;
const notificationContent = {
notification: {
title:"notification",
body: "friend request",
icon: "default"
}
};
return admin.messaging().sendToDevice(tokenId, notificationContent).then(result => {
console.log("Notification sent!");
});
});
});
});
答案 0 :(得分:2)
您应该通过对token_id
文档进行doc.data().token_id
来获得User
的值。我已经相应地修改了您的代码,请参见下文:
exports.sendoNotification = functions.firestore
.document('/Users/{user_id}/Notification/{notification_id}')
.onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification from : ', user_id);
var userRef = firestore.collection('Users').doc(user_id);
return userRef
.get()
.then(doc => {
if (!doc.exists) {
console.log('No such User document!');
throw new Error('No such User document!'); //should not occur normally as the notification is a "child" of the user
} else {
console.log('Document data:', doc.data());
console.log('Document data:', doc.data().token_id);
return true;
}
})
.catch(err => {
console.log('Error getting document', err);
return false;
});
});
请注意:
get()
函数返回的promise。 如果您不熟悉Cloud Functions,我建议您观看以下官方视频系列“ Learning Cloud Functions for Firebase”(请参阅https://firebase.google.com/docs/functions/video-series/),尤其是三个名为“ Learn JavaScript Promises”的视频。 ,解释了在事件触发的Cloud Functions中我们应该如何以及为什么应该链接和返回Promise。
已经回答了您的问题(即“如何获取token_id?”),我想提请您注意以下事实:在您的代码中,return Promise.all([getDoc]).then()
代码位于catch()
内,因此无法按预期工作。您应该修改代码的这一部分,并将其包括在promises链中。如果您在这方面需要帮助,请提出一个新问题。