How do you access a DocumentReference object stored in Firestore from a Cloud Function?











up vote
0
down vote

favorite












In my Firestore database I store DocumentReferences to users so that I am always using up-to-date user data such as username, profile pictures, and auth tokens.



I am also implementing Cloud Functions to listen for database triggers so that I can send notifications to those specific users about activity related to their posts.



This is where I run into trouble, because I do not know how to use the stored reference object properly inside the Node.js function when I access it like all other database information.



The following is my function code:



exports.countNameChanges = functions.firestore
.document('posts/{postId}')
.onUpdate((change, context) => {
// Retrieve the current and previous value
const data = change.after.data();
const previousData = change.before.data();
var registrationToken = '';

var notification = '';
var postTitle = data.statement;
var userRef = data.userRef; //This is my `DocumentReference` object

if (data.interactionCount > previousData.interactionCount && data.postTypeId == 2131165321) notification = 'You recieved a new comment!';
if (data.interactionCount > previousData.interactionCount && data.postTypeId == 2131165335) notification = 'You recieved a new vote!';
if (data.likes > previousData.likes) notification = 'You have a new post like!' ;
if (data.dislikes > previousData.dislikes) notification = 'You have a new post dislike!' ;

admin.firestore()
.doc(userRef) //This is my `DocumentReference` object
.get()
.then(doc => {
registrationToken = doc.data().token;

var payload = {
data: {
title: postTitle,
body: notification
},
token: registrationToken
};

admin.messaging().send(payload)
.then((response) => {
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
})
});

});

});


My Function Log



enter image description here



I would assume that the DocumentReference object would be easy to work with
inside a Cloud Function since the object is supported for direct storage into Firestore, but I can't figure it out.










share|improve this question


























    up vote
    0
    down vote

    favorite












    In my Firestore database I store DocumentReferences to users so that I am always using up-to-date user data such as username, profile pictures, and auth tokens.



    I am also implementing Cloud Functions to listen for database triggers so that I can send notifications to those specific users about activity related to their posts.



    This is where I run into trouble, because I do not know how to use the stored reference object properly inside the Node.js function when I access it like all other database information.



    The following is my function code:



    exports.countNameChanges = functions.firestore
    .document('posts/{postId}')
    .onUpdate((change, context) => {
    // Retrieve the current and previous value
    const data = change.after.data();
    const previousData = change.before.data();
    var registrationToken = '';

    var notification = '';
    var postTitle = data.statement;
    var userRef = data.userRef; //This is my `DocumentReference` object

    if (data.interactionCount > previousData.interactionCount && data.postTypeId == 2131165321) notification = 'You recieved a new comment!';
    if (data.interactionCount > previousData.interactionCount && data.postTypeId == 2131165335) notification = 'You recieved a new vote!';
    if (data.likes > previousData.likes) notification = 'You have a new post like!' ;
    if (data.dislikes > previousData.dislikes) notification = 'You have a new post dislike!' ;

    admin.firestore()
    .doc(userRef) //This is my `DocumentReference` object
    .get()
    .then(doc => {
    registrationToken = doc.data().token;

    var payload = {
    data: {
    title: postTitle,
    body: notification
    },
    token: registrationToken
    };

    admin.messaging().send(payload)
    .then((response) => {
    console.log('Successfully sent message:', response);
    })
    .catch((error) => {
    console.log('Error sending message:', error);
    })
    });

    });

    });


    My Function Log



    enter image description here



    I would assume that the DocumentReference object would be easy to work with
    inside a Cloud Function since the object is supported for direct storage into Firestore, but I can't figure it out.










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      In my Firestore database I store DocumentReferences to users so that I am always using up-to-date user data such as username, profile pictures, and auth tokens.



      I am also implementing Cloud Functions to listen for database triggers so that I can send notifications to those specific users about activity related to their posts.



      This is where I run into trouble, because I do not know how to use the stored reference object properly inside the Node.js function when I access it like all other database information.



      The following is my function code:



      exports.countNameChanges = functions.firestore
      .document('posts/{postId}')
      .onUpdate((change, context) => {
      // Retrieve the current and previous value
      const data = change.after.data();
      const previousData = change.before.data();
      var registrationToken = '';

      var notification = '';
      var postTitle = data.statement;
      var userRef = data.userRef; //This is my `DocumentReference` object

      if (data.interactionCount > previousData.interactionCount && data.postTypeId == 2131165321) notification = 'You recieved a new comment!';
      if (data.interactionCount > previousData.interactionCount && data.postTypeId == 2131165335) notification = 'You recieved a new vote!';
      if (data.likes > previousData.likes) notification = 'You have a new post like!' ;
      if (data.dislikes > previousData.dislikes) notification = 'You have a new post dislike!' ;

      admin.firestore()
      .doc(userRef) //This is my `DocumentReference` object
      .get()
      .then(doc => {
      registrationToken = doc.data().token;

      var payload = {
      data: {
      title: postTitle,
      body: notification
      },
      token: registrationToken
      };

      admin.messaging().send(payload)
      .then((response) => {
      console.log('Successfully sent message:', response);
      })
      .catch((error) => {
      console.log('Error sending message:', error);
      })
      });

      });

      });


      My Function Log



      enter image description here



      I would assume that the DocumentReference object would be easy to work with
      inside a Cloud Function since the object is supported for direct storage into Firestore, but I can't figure it out.










      share|improve this question













      In my Firestore database I store DocumentReferences to users so that I am always using up-to-date user data such as username, profile pictures, and auth tokens.



      I am also implementing Cloud Functions to listen for database triggers so that I can send notifications to those specific users about activity related to their posts.



      This is where I run into trouble, because I do not know how to use the stored reference object properly inside the Node.js function when I access it like all other database information.



      The following is my function code:



      exports.countNameChanges = functions.firestore
      .document('posts/{postId}')
      .onUpdate((change, context) => {
      // Retrieve the current and previous value
      const data = change.after.data();
      const previousData = change.before.data();
      var registrationToken = '';

      var notification = '';
      var postTitle = data.statement;
      var userRef = data.userRef; //This is my `DocumentReference` object

      if (data.interactionCount > previousData.interactionCount && data.postTypeId == 2131165321) notification = 'You recieved a new comment!';
      if (data.interactionCount > previousData.interactionCount && data.postTypeId == 2131165335) notification = 'You recieved a new vote!';
      if (data.likes > previousData.likes) notification = 'You have a new post like!' ;
      if (data.dislikes > previousData.dislikes) notification = 'You have a new post dislike!' ;

      admin.firestore()
      .doc(userRef) //This is my `DocumentReference` object
      .get()
      .then(doc => {
      registrationToken = doc.data().token;

      var payload = {
      data: {
      title: postTitle,
      body: notification
      },
      token: registrationToken
      };

      admin.messaging().send(payload)
      .then((response) => {
      console.log('Successfully sent message:', response);
      })
      .catch((error) => {
      console.log('Error sending message:', error);
      })
      });

      });

      });


      My Function Log



      enter image description here



      I would assume that the DocumentReference object would be easy to work with
      inside a Cloud Function since the object is supported for direct storage into Firestore, but I can't figure it out.







      javascript android firebase-cloud-messaging google-cloud-firestore google-cloud-functions






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 8 at 21:59









      Jantzilla

      4501316




      4501316
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          If userRef is a DocumentReference type object, then just call get() on it directly. Don't pass it to doc(). You're only supposed to pass string type objects to doc().



          userRef.get().then(...)





          share|improve this answer





















          • I had already tried this, except I included the admin prefix. I have since simply replaced the DocumentReference object with a string of the specific document in Firestore and refactored my app to simply build the reference from that.
            – Jantzilla
            Nov 9 at 0:08










          • What do you mean "I included the admin prefix"? None of what you're saying here makes sense to me.
            – Doug Stevenson
            Nov 9 at 3:48










          • I just meant I did what you suggested before asking and was unsuccessful.
            – Jantzilla
            Nov 9 at 5:07











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53216788%2fhow-do-you-access-a-documentreference-object-stored-in-firestore-from-a-cloud-fu%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote













          If userRef is a DocumentReference type object, then just call get() on it directly. Don't pass it to doc(). You're only supposed to pass string type objects to doc().



          userRef.get().then(...)





          share|improve this answer





















          • I had already tried this, except I included the admin prefix. I have since simply replaced the DocumentReference object with a string of the specific document in Firestore and refactored my app to simply build the reference from that.
            – Jantzilla
            Nov 9 at 0:08










          • What do you mean "I included the admin prefix"? None of what you're saying here makes sense to me.
            – Doug Stevenson
            Nov 9 at 3:48










          • I just meant I did what you suggested before asking and was unsuccessful.
            – Jantzilla
            Nov 9 at 5:07















          up vote
          0
          down vote













          If userRef is a DocumentReference type object, then just call get() on it directly. Don't pass it to doc(). You're only supposed to pass string type objects to doc().



          userRef.get().then(...)





          share|improve this answer





















          • I had already tried this, except I included the admin prefix. I have since simply replaced the DocumentReference object with a string of the specific document in Firestore and refactored my app to simply build the reference from that.
            – Jantzilla
            Nov 9 at 0:08










          • What do you mean "I included the admin prefix"? None of what you're saying here makes sense to me.
            – Doug Stevenson
            Nov 9 at 3:48










          • I just meant I did what you suggested before asking and was unsuccessful.
            – Jantzilla
            Nov 9 at 5:07













          up vote
          0
          down vote










          up vote
          0
          down vote









          If userRef is a DocumentReference type object, then just call get() on it directly. Don't pass it to doc(). You're only supposed to pass string type objects to doc().



          userRef.get().then(...)





          share|improve this answer












          If userRef is a DocumentReference type object, then just call get() on it directly. Don't pass it to doc(). You're only supposed to pass string type objects to doc().



          userRef.get().then(...)






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 8 at 23:20









          Doug Stevenson

          67.1k87998




          67.1k87998












          • I had already tried this, except I included the admin prefix. I have since simply replaced the DocumentReference object with a string of the specific document in Firestore and refactored my app to simply build the reference from that.
            – Jantzilla
            Nov 9 at 0:08










          • What do you mean "I included the admin prefix"? None of what you're saying here makes sense to me.
            – Doug Stevenson
            Nov 9 at 3:48










          • I just meant I did what you suggested before asking and was unsuccessful.
            – Jantzilla
            Nov 9 at 5:07


















          • I had already tried this, except I included the admin prefix. I have since simply replaced the DocumentReference object with a string of the specific document in Firestore and refactored my app to simply build the reference from that.
            – Jantzilla
            Nov 9 at 0:08










          • What do you mean "I included the admin prefix"? None of what you're saying here makes sense to me.
            – Doug Stevenson
            Nov 9 at 3:48










          • I just meant I did what you suggested before asking and was unsuccessful.
            – Jantzilla
            Nov 9 at 5:07
















          I had already tried this, except I included the admin prefix. I have since simply replaced the DocumentReference object with a string of the specific document in Firestore and refactored my app to simply build the reference from that.
          – Jantzilla
          Nov 9 at 0:08




          I had already tried this, except I included the admin prefix. I have since simply replaced the DocumentReference object with a string of the specific document in Firestore and refactored my app to simply build the reference from that.
          – Jantzilla
          Nov 9 at 0:08












          What do you mean "I included the admin prefix"? None of what you're saying here makes sense to me.
          – Doug Stevenson
          Nov 9 at 3:48




          What do you mean "I included the admin prefix"? None of what you're saying here makes sense to me.
          – Doug Stevenson
          Nov 9 at 3:48












          I just meant I did what you suggested before asking and was unsuccessful.
          – Jantzilla
          Nov 9 at 5:07




          I just meant I did what you suggested before asking and was unsuccessful.
          – Jantzilla
          Nov 9 at 5:07


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53216788%2fhow-do-you-access-a-documentreference-object-stored-in-firestore-from-a-cloud-fu%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          這個網誌中的熱門文章

          Academy of Television Arts & Sciences

          L'Équipe

          1995 France bombings