【问题标题】:How to get particular field value in node.js from Cloud Firestore database?如何从 Cloud Firestore 数据库中获取 node.js 中的特定字段值?
【发布时间】:2019-02-01 01:21:35
【问题描述】:

如何在节点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!");

			});
		});
	});

});

【问题讨论】:

    标签: node.js firebase push-notification google-cloud-firestore google-cloud-functions


    【解决方案1】:

    您应该通过在User 文档上执行doc.data().token_id 来获得token_id 的值。我已经相应地调整了你的代码,见下文:

    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;
          });
      });
    

    注意:

    • 我已将 ref 从 cityRef 更改为 userRef,只是一个细节;
    • 更重要的是,我们返回由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() 内,因此无法按预期工作。您应该修改这部分代码并将其包含在 Promise 链中。如果您在这部分需要帮助,请提出一个新问题。

    【讨论】:

    • 效果很好。谢谢你的解释,雷诺塔内克。
    猜你喜欢
    • 2020-03-29
    • 2019-03-03
    • 2020-12-04
    • 2021-11-20
    • 2021-12-02
    • 2021-04-25
    • 2017-12-08
    • 1970-01-01
    相关资源
    最近更新 更多