【问题标题】:Firebase Functions - Get data from the main collection when a document is created in a sub collectionFirebase 函数 - 在子集合中创建文档时从主集合获取数据
【发布时间】:2021-05-18 11:40:27
【问题描述】:

这就是我的 Firestore 数据库的样子

  • Feed(主集合)
    • Feed 1(主集合下的文档)
    • 饲料 2
      • cmets(子系列)
        • 评论 1(子集合中的文档)
        • 评论2

当使用 firebase 功能添加新评论时,我正在尝试访问 main-collection 下文档中的信息。有没有办法访问这些信息?

我当前的代码,我只能访问commentDoc数据

exports.newComment=functions.firestore.document('Feed/{FeedDoc}/comments/{commentDoc}').onCreate((snap, context) => {
const commentData = snap.data()
}

【问题讨论】:

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


    【解决方案1】:

    您可以使用DocumentReferenceCollectionReferenceparent 方法执行以下操作:

    exports.newComment=functions.firestore.document('Feed/{FeedDoc}/comments/{commentDoc}')
     .onCreate(async (snap, context) => {   // Note the async keyword
        const commentData = snap.data();
    
        const feedDocRef = snap.ref.parent.parent;
        const feedSnap = await feedDocRef.get();
        // ...
    });
    

    或者您可以使用context.params

    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp();
    
    exports.newComment=functions.firestore.document('Feed/{FeedDoc}/comments/{commentDoc}').onCreate(async (snap, context) => {
       const commentData = snap.data();
    
       const feedDocId = context.params.FeedDoc;
       const feedSnap = await admin.firestore().doc(`Feed/${FeedDocId}`).get();
       // ...
    });
    

    【讨论】:

      猜你喜欢
      • 2020-08-15
      • 2018-07-01
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2021-01-21
      • 2021-07-20
      • 2021-07-25
      相关资源
      最近更新 更多