【问题标题】:How do you access a DocumentReference object stored in Firestore from a Cloud Function?如何从 Cloud Function 访问存储在 Firestore 中的 DocumentReference 对象?
【发布时间】:2019-04-12 11:53:47
【问题描述】:

在我的Firestore 数据库中,我将DocumentReferences 存储给用户,以便我始终使用最新的用户数据,例如用户名、个人资料图片和身份验证令牌。

我还在实现Cloud Functions 来监听数据库触发器,以便我可以向这些特定用户发送与他们的帖子相关的活动的通知。

这是我遇到麻烦的地方,因为当我像访问所有其他数据库信息一样访问 Node.js 函数时,我不知道如何正确使用存储的引用对象。

以下是我的功能代码:

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

   });

});

我的功能日志

我认为DocumentReference 对象很容易使用 在Cloud Function 内,因为支持将对象直接存储到Firestore,但我无法弄清楚。

【问题讨论】:

    标签: javascript android firebase-cloud-messaging google-cloud-firestore google-cloud-functions


    【解决方案1】:

    如果userRef是一个DocumentReference类型的对象,那么直接调用get()就可以了。不要将其传递给doc()。你只应该将字符串类型的对象传递给doc()。

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

    【讨论】:

    • 我已经尝试过了,除了我添加了admin 前缀。从那以后,我只是用Firestore 中的特定文档字符串替换了DocumentReference 对象,并重构了我的应用程序以简单地从中构建引用。
    • “我包含了管理员前缀”是什么意思?你在这里说的对我来说毫无意义。
    • 我的意思是我在询问之前按照您的建议做了,但没有成功。
    猜你喜欢
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2019-02-14
    • 2018-03-19
    • 2020-11-27
    • 1970-01-01
    相关资源
    最近更新 更多