node js firestore函数日志错误 - TypeError:无法在exports.observeMessages.functions.database.ref.onCreate中读取未定义的属性'uid'

时间:2018-06-02 13:29:38

标签: node.js google-cloud-firestore google-cloud-functions

我在我的firestore功能日志中收到此错误

TypeError:无法读取undefined的属性'uid'     at exports.observeMessages.functions.database.ref.onCreate.event(/user_code/index.js:23:27)

这是我的功能代码

  exports.observeMessages = functions.database.ref('/user-messages/{uid}/{fromId}/{messageId}')
.onCreate(event => {

var uid = event.params.uid;
var fromUid = event.params.fromId
var messageId = event.params.messageId

// let's log out some messages

console.log('User: ' + uid + 'was just messaged by: ' + fromId);



      //firestore - get users fcm token from firestore to send a push messaged


var Ref = db.collection('Users').doc(uid);
var getDoc = Ref.get()
.then(doc => {
  if (!doc.exists) {
  return console.log('No such document!');
  } else {
   console.log('Document data:', doc.data());


   var userUID = parseFloat(doc.data().uid);

      return console.log(userUID);
  }
})
.catch(err => {
  return console.log('Error getting document', err);
});

1 个答案:

答案 0 :(得分:0)

您可能正在使用Firebase SDK for Cloud Functions的1.0版。+但您的代码使用的是旧语法(SDK< 1.0)。您可以在package.json文件中验证云功能的版本。

有关语法更改的信息,请参阅此文档项:https://firebase.google.com/docs/functions/beta-v1-diff

您应该按如下方式修改您的代码(请参阅前三行"此处修改"):

exports.observeMessages = functions.database.ref('/user-messages/{uid}/{fromId}/{messageId}')
.onCreate((snap, context) => {

var uid = context.params.uid;  // <- Here modify
var fromUid = context.params.fromId  // <- Here modify
var messageId = context.params.messageId  // <- Here modify

// let's log out some messages

console.log('User: ' + uid + 'was just messaged by: ' + fromId);

      //firestore - get users fcm token from firestore to send a push messaged

var Ref = db.collection('Users').doc(uid);
return Ref.get(). // <- Here modify
.then(doc => {
  if (!doc.exists) {
     console.log('No such document!');  // <- Here modify 
      return false;  // <- Here modify 
  } else {
   console.log('Document data:', doc.data());


   var userUID = parseFloat(doc.data().uid);

      console.log(userUID);  // <- Here modify
      //return a promise like the one returned by the sendToDevice method 
      //See https://firebase.google.com/docs/reference/admin/node/admin.messaging.Messaging#sendToDevice

  }
})
.catch(err => {
  console.log('Error getting document', err);  // <- Here modify, no need to return anything here
});

请注意,您还应修改代码的其他部分,而不仅仅是顶部的3行。事实上,您需要在云函数中返回一个承诺。请参阅上面的其他修改,再次使用&#34;此处修改&#34;评价。

我很好(但强烈地:-))建议你观看Firebase小组的这些视频:https://www.youtube.com/watch?v=7IkUgCLr5oA&t=28shttps://www.youtube.com/watch?v=652XeeKNHSk,它们解释了这些关键概念。