firebase云函数无法读取未定义的属性“ ref”

时间:2018-10-14 08:49:05

标签: javascript firebase firebase-realtime-database google-cloud-functions

当我想从实时数据库更新Cloud Firestore时,我部署了以下代码,但出现错误。

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

const firestore = functions.firestore;

exports.onUserStatusChange = functions.database
    .ref('/status/{userId}')
    .onUpdate(event => {

        var db = admin.firestore();


        //const usersRef = firestore.document('/users/' + event.params.userId);
        const usersRef = db.collection("users");
        var snapShot = event.data;

        return event.data.ref.once('value')
            .then(statusSnap => snapShot.val())
            .then(status => {
                if (status === 'offline'){
                    usersRef
                        .doc(event.params.userId)
                        .set({
                            online: false,
                            last_active: Date.now()
                        }, {merge: true});
                }
            })
    });

TypeError:无法读取未定义的属性“ ref”     在exports.onUserStatusChange.functions.database.ref.onUpdate.event(/user_code/index.js:18:20)     在cloudFunctionNewSignature(/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23)     在cloudFunction(/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20)     在/var/tmp/worker/worker.js:733:24     在process._tickDomainCallback(internal / process / next_tick.js:135:7)

2 个答案:

答案 0 :(得分:2)

您似乎已获得Cloud Functions for Firebase Beta版的代码。语法在1.0版本中已更改。来自documentation on upgrading your Cloud Functions

或onWrite和onUpdate事件,data参数具有before和after字段。其中每个都是DataSnapshot,其管理方法与admin.database.DataSnapshot中的可用方法相同。例如:

  

之前(<= v0.9.1)

exports.dbWrite = functions.database.ref('/path').onWrite((event) => {
  const beforeData = event.data.previous.val(); // data before the write
  const afterData = event.data.val(); // data after the write
});
     

现在(> = v1.0.0)

exports.dbWrite = functions.database.ref('/path').onWrite((change, context) => {
  const beforeData = change.before.val(); // data before the write
  const afterData = change.after.val(); // data after the write
});

因此您将要使用:

  • .onUpdate((change, context) => {声明功能,而不是.onUpdate(event => {
  • 使用change.after而不是event.data来引用数据
  • 使用change.after.ref.once('value')代替event.data.ref.once('value')

由于此代码似乎主要是从某个地方复制的,因此建议从那里获取更新的版本。例如,您的代码可能基于的Firestore文档在此处包含最新示例:https://firebase.google.com/docs/firestore/solutions/presence#updating_globally

答案 1 :(得分:0)

请尝试更改以下代码,因为事件的firebase函数不再具有两个属性。因此,参考位置是:

.onUpdate((event,context) => {
 ....
return event.ref.once('value')
...

event.data不再存在,而more infoevent.val()event具有properties like