James Gitonga
James Gitonga

Reputation: 101

Querying a sub-collection in firestore using cloud functions

I am fairly new to cloud functions and I am trying to create a notifications feature in my app. The notifications are stored in a sub-collection. The error shown at the logs is

TypeError: Cannot read property 'first_name' of undefined at Promise.all.then.result (/srv/index.js:29:41).

What could be the issue?

'use-strict'

const functions = require('firebase-functions');
const admin = require ('firebase-admin');
admin.initializeApp(functions.config().firebase);


exports.sendNotification = functions.firestore.document("Employee_Details/{user_id}/Notifications/{notification_id}")
.onWrite((change , context) =>{

  const user_id = context.params.user_id;
  const notification_id = context.params.notification_id;

  //console.log("User ID:" + user_id + "| Notification ID : " + notification_id);

  return admin.firestore().collection("Employee_Details").doc(user_id).collection("Notifications").doc(notification_id).get().then(queryResult => {

    const from_user_id = queryResult.data().from;

    const from_data = admin.firestore().collection("Employee_Details").doc(from_user_id).get();
    const to_data = admin.firestore().collection("Employee_Details").doc(user_id).get();

  //  console.log("FROM_DAT:" + from_data + "TO_DATA:" + to_data);


    return Promise.all([from_data , to_data]).then(result => {


      const from_name = result[0].data().first_name;
      const to_name =  result[1].data().first_name;

      return console.log("FROM: "+ from_name + "TO:" + to_name);


    });


  });



});

Firestore structure

Sub-collection

Upvotes: 1

Views: 571

Answers (1)

Ajordat
Ajordat

Reputation: 1392

If the screenshots you have attached belong to the values you are trying to retrieve, there's no document in Employee_Details with the id at Employee_Details.Gh82W1.Notifications.KR0CN4.from. This is why result[0] is undefined, because it couldn't retrieve anything.

Is there any reason why you think you are using old syntax? It seems correct to me. You are using the same methods as in the sample code for nodejs. The only change I would do is to avoid using admin.firestore() every time. Something like this:

const db = admin.firestore();
const from_data = db.collection("Employee_Details").doc(from_user_id).get();
const to_data = db.collection("Employee_Details").doc(user_id).get();

But that's a personal preference.

Upvotes: 1

Related Questions