访问云功能中的云Firestore文档

Gar*_*aye 9 firebase google-cloud-functions google-cloud-firestore

在我的Google Firebase Firstore数据库中,我想收集汇总数据,例如集合中有多少文档.由于Firestore不提供聚合查询,因此我尝试编写一个云函数,每次将文档添加到数据库时都会增加一个字段,该数据库将包含集合所具有的文档数.

我遇到的问题是我不能为我的生活弄清楚如何使用nodejs在云功能中从Firestore获取文档.

这是我正在做的事情:

在我的index.js文件的顶部,我配置管理SDK,你喜欢这个:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
Run Code Online (Sandbox Code Playgroud)

那么对于我的云功能,我这样做:

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]);
    });
});
Run Code Online (Sandbox Code Playgroud)

我最终得到了错误:

TypeError:无法在Promise.all.then.snapshot中读取null的属性"global_post_count"

我认为这意味着我的查询有问题,但我不知道是什么.无论是usersposts是根级别的集合.

我也得到一个警告:

结算帐户未配置.无法访问外部网络,配额受到严格限制.

从我在网上看到的内容来看,我认为不会影响它,但我认为值得注意.

请帮忙.

Dou*_*son 15

看起来你已经写了一个Firestore触发器,但是后来进入实时数据库进行查询:

const userDocRef = admin.database().ref('/users').orderByChild("user_id").equalTo(senderID).once('value')
const ledgerDocRef = admin.database().ref('/posts/ledger').once('value');
Run Code Online (Sandbox Code Playgroud)

如果您的RTDB为空,这些查询也将为空.

要查询Firestore,您需要使用admin.firestore()而不是admin.database().Firestore 与RTDB 有很多不同的API(通过我刚刚链接的Cloud SDK),但它们在某些方面类似.