Sj Raza
Sj Raza

Reputation: 103

How to get particular field value in node.js from Cloud Firestore database?

How to get that token_id in node js?

database image

x

Index.js code is below, by this code it gives all the data stored in user_id but i'm unable to get only that particular field of {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!");

			});
		});
	});

});

Upvotes: 10

Views: 8257

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83191

You should get the value of token_id by doing doc.data().token_id on the User doc. I've adapted you code accordingly, see below:

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

Note that:

  • I've changed the ref from cityRef to userRef, just a detail;
  • Much more important, we return the promise returned by the get() function.

If you are not familiar with Cloud Functions I would suggest that you watch the following official Video Series "Learning Cloud Functions for Firebase" (see https://firebase.google.com/docs/functions/video-series/), and in particular the three videos titled "Learn JavaScript Promises", which explain how and why we should chain and return promises in event triggered Cloud Functions.


Having answered your question (i.e. "How to get that token_id?"), I would like to draw your attention on the fact that, in your code, the return Promise.all([getDoc]).then() piece of code is within the catch() and therefore will not work as you expect. You should adapt this part of the code and include it in the promises chain. If you need help on this part, please ask a new question.

Upvotes: 12

Related Questions