Как получить конкретное значение поля в node.js из базы данных Cloud Firestore? - PullRequest
0 голосов
/ 26 августа 2018

Как получить этот token_id в узле js?

образ базы данных

x

Код 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!");

			});
		});
	});

});

1 Ответ

0 голосов
/ 26 августа 2018

Вы должны получить значение 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;
      });
  });

Обратите внимание:

  • Я изменил ссылку с cityRef на userRef, просто деталь;
  • Гораздо важнее, что мы возвращаем обещание, возвращаемое функцией get().

Если вы не знакомы с облачными функциями, я бы посоветовал вам посмотреть следующий официальный видеосериал «Изучение облачных функций для Firebase» (см. https://firebase.google.com/docs/functions/video-series/), и, в частности, три видео под названием«Изучите обещания JavaScript», в которых объясняется, как и почему мы должны связывать и возвращать обещания в облачных функциях, запускаемых событиями.


Ответив на ваш вопрос (т. Е. «Как получить этот token_id?»), Я хотел бы обратить ваше внимание на тот факт, что в вашем коде кусок кода return Promise.all([getDoc]).then() находится внутри catch() и поэтому не будет работать так, как вы ожидаете. Вам следует адаптировать эту часть кодаи включите его в цепочку обещаний. Если вам нужна помощь в этой части, задайте новый вопрос.

...