Sj *_*aza 7 push-notification node.js firebase google-cloud-functions google-cloud-firestore
如何在节点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!");
});
});
});
});Run Code Online (Sandbox Code Playgroud)
Ren*_*nec 10
你应该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;
});
});
Run Code Online (Sandbox Code Playgroud)
注意:
get()函数返回的承诺。如果您不熟悉 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(),因此不会按您的预期工作。您应该修改这部分代码并将其包含在承诺链中。如果您在这方面需要帮助,请提出一个新问题。
| 归档时间: |
|
| 查看次数: |
5730 次 |
| 最近记录: |