从Node.js云功能添加Firebase Firestore数据库侦听器

时间:2018-04-23 15:33:40

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

我的问题是,无法从write DB回调中读取数据,请查看下面的更多详细信息

我正在使用带有node.js云功能的firestore,我需要将DB监听器设置为消息集合,下面是设置监听器的数据和数据结构的代码,我的问题请查看以下内容数据结构

First levent collection

这是第二级和添加的消息 Second level collection and the added item to the colection

exports.sendNotificationDependsOnEvent = functions.firestore.document('events/{event}/messages/{message}')
    .onCreate((snap, context) => {
        const document = snap.val();
         // I tried snap.val() and it's not worked
         //and I tried snap.data (give me very long un related data)
         //and I tried snap.data() and it throwing exception (data is not a function)
         //and I tried snap.current.val (and no result for that)

        const text = document.message;
        console.log("Step 3 : get message text : " + text);
});

建议我如何从上述数据中读取数据

1 个答案:

答案 0 :(得分:1)

您的问题很可能来自snap不存在的事实。您构建引用的方式可能有错误。

详见文档(https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document),建议在尝试获取字段值之前检查文档是否存在。

从上面引用的文档中查看此示例(对于node.js):

var cityRef = db.collection('cities').doc('SF');
var getDoc = cityRef.get()
.then(doc => {
  if (!doc.exists) {
    console.log('No such document!');
  } else {
    console.log('Document data:', doc.data());
  }
})
.catch(err => {
  console.log('Error getting document', err);
});

您可以在代码中检查是否真的存在,如下所示?

exports.sendNotificationDependsOnEvent = functions.firestore.document('events/{event}/messages/{message}')
.onCreate((snap, context) => {
    if (!snap.exists) {
      console.log('No such document!');
    } else {
      console.log('Document data:', snap.data());
    }
});

控制台将登录功能日志。