javascript - 从 Node.js Cloud Functions 添加 Firebase Firestore DB 监听器

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

我的问题,无法从写数据库回调中读取数据,查看下面了解更多详情

我正在使用带有 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);
});

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

最佳答案

您的问题很可能是因为 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);
});

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

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

控制台将登录功能日志。

关于javascript - 从 Node.js Cloud Functions 添加 Firebase Firestore DB 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49984831/

相关文章:

javascript - 类型错误 "string"must be a string, Buffer, or ArrayBuffer

java - 当我在 GridView 中使用 setOnItemClickListener 返回 null

regex - 自动正则表达式学习器?

javascript - 一旦用户鼠标离开文本字段就运行函数

javascript - 选择更改时设置 Chrome 存储空间

JavaScript 变量/字符串函数?

mongodb - 带有express和mongoDB的NodeJS应用程序

ios - Firebase Auth 方法 createUser 未显示正确的参数

Firebase 消息传递,在哪里获取服务器 key ?

javascript - 如何遍历 JavaScript 对象以找到父对象