在我的 Google Firebase Firstore 数据库中,我想收集聚合数据,例如一个集合有多少个文档。由于 Firestore 不提供聚合查询,我正在尝试编写一个云函数,每次将文档添加到数据库时都会增加一个字段,该数据库将包含集合拥有的文档数。
我遇到的问题是我一生都无法弄清楚如何使用 nodejs 在云函数中从 Firestore 中获取文档。
这是我在做什么:
在我的顶部 index.js
文件我配置了管理 SDK,你有什么喜欢的:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
然后对于我的云功能,我这样做:
exports.createPost = functions.firestore
.document('posts/{post_id}')
.onCreate(event => {
// Get the post object
var post = event.data.data();
var senderID = post["sender_id"]; // This is not null
// Access to user's document and the main ledger document
const userDocRef = admin.database().ref('/users').orderByChild("user_id").equalTo(senderID).once('value')
const ledgerDocRef = admin.database().ref('/posts/ledger').once('value');
return Promise.all([userDocRef, ledgerDocRef]).then(snapshot => {
const user = snapshot[0].val();
const ledger = snapshot[1].val();
console.log("user => "+user); // Logs: user => null
console.log("ledger => "+ledger); // Logs: ledger => null
const userPostCount = user["user_name"];
const globalPostCount = ledger["global_post_count"] + 1;
const userUpdate = user.update({"post_count" : userPostCount});
const ledgerUpdate = ledger.update({"global_post_count" : globalPostCount});
return Promise.all([userUpdate, ledgerUpdate]);
});
});
我最终得到了错误:
TypeError: Cannot read property 'global_post_count' of null at Promise.all.then.snapshot
我认为这意味着我的查询有问题,但我不知道是什么。两者
users
和 posts
是根级集合。我也收到一条警告说:
Billing account not configured. External network is not accessible and quotas are severely limited.
从我在网上阅读的内容来看,我认为这不会影响它,但我认为值得注意。
请帮忙。
最佳答案
看起来您已经编写了 Firestore 触发器,但随后正在访问实时数据库进行查询:
const userDocRef = admin.database().ref('/users').orderByChild("user_id").equalTo(senderID).once('value')
const ledgerDocRef = admin.database().ref('/posts/ledger').once('value');
如果您的 RTDB 为空,这些查询也将最终为空。
要查询 Firestore,您需要使用
admin.firestore()
而不是 admin.database()
. Firestore 有一个 mostly different API (通过我刚刚链接的 Cloud SDK)而不是 RTDB,但它们在某些方面是相似的。
关于firebase - 访问云功能中的云 Firestore 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46782423/