【问题标题】:Firebase Functions - Get data from the main collection when a document is created in a sub collectionFirebase 函数 - 在子集合中创建文档时从主集合获取数据
【发布时间】:2021-05-18 11:40:27
【问题描述】:
这就是我的 Firestore 数据库的样子
当使用 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】:
您可以使用DocumentReference 和CollectionReference 的parent 方法执行以下操作:
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();
// ...
});