Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

			});
		});
	});

});
like image 720
Sj Raza Avatar asked Aug 26 '18 05:08

Sj Raza


People also ask

How do I get data from firestore to node js?

To read your data from Firestore, use the get() method. To read from a collection, specify a collection() before calling get() . Or, if you need to read from a document, specify a doc() before calling get() . // get collection const users = await db.

Can I use firestore with node js?

If you are developing a Web or Node. js application that accesses Cloud Firestore on behalf of end users, use the firebase Client SDK. Note: This Cloud Firestore Server SDK does not support Firestore databases created in Datastore mode. To access these databases, use the Datastore SDK.


1 Answers

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.

like image 151
Renaud Tarnec Avatar answered Oct 20 '22 22:10

Renaud Tarnec