首页 > 解决方案 > firebase云函数中更新的firestore文档的变化数据返回undefined

问题描述

我正在使用 firestore onUpdate 触发器并尝试获取更新文档的数据(字段名称、新值)。

const newValue = change.after.data();

const name = newValue.name;

我希望通过添加到他的个人资料中的新标记来通知用户,例如:

新的出席分数是 50

但是当我在通知正文中显示它们时,它会显示:

收到通知

这是完整的云函数片段:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();
//functions.config().firebase
exports.updateUser = functions.firestore
    .document('stuThird/{userId}/stuMarks/{markId}')
    .onUpdate((change, context) => {
      // Get an object representing the document
      // e.g. {'name': 'Marie', 'age': 66}
      const newValue = change.after.data();

      // ...or the previous value before this update
      const previousValue = change.before.data();

      // access a particular field as you would any JS property
      const name = newValue.name;
      var body = ' the new mark of' + name + 'is'+ newValue;
      if(newValue){

      var message = {
        notification: {
            title: 'new mark changed',
            body:   body,
        },
        topic: 'bebo'
    };
  }

    // Send the message.
    return admin.messaging().send(message)
        .then((message) => {
           return console.log('Successfully sent message:', message);
        })
        .catch((error) => {
            console.error('Error sending message:', error);
        });
      // perform desired operations ...
    });

**

这是数据库:

** 第一个结构部分 第二结构部分

标签: node.jsfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


推荐阅读