Firestore事务未在Cloud Functions中查找数据

时间:2018-02-15 00:09:19

标签: javascript firebase google-cloud-functions google-cloud-firestore

我正在为我的应用编写云功能。我使用的是Firestore而不是RTDB。无论出于何种原因,我的函数都没有正确地从Firestore读取值。当它尝试读取值时,会显示undefined。我希望这个函数做的就是增加following_count值,我知道它正在查找正确的位置,因为它用NaN替换了该值。如何更改我的代码以便正确读取Firestore值?提前致谢

exports.countfollowerschangeFirestore = functions.firestore.document('users/{userid}/following/{followingid}').onWrite(event => {
    const collectionRef = event.data.ref.parent;
    const countRef = collectionRef.parent;
    var new_count;

    var transaction = db.runTransaction(t => {
        return t.get(countRef)
            .then(doc => {
                if (doc.exists) {
                    //This is where it is trying to read the data which should be a 0.
                    var new_count = doc.data.following_count + 1;
                    console.log(doc.data.following_count);
                    t.update(countRef, { following_count: new_count });
                }
            });
    }).then(result => {
        console.log('Transaction success!');
    })
    .catch(err => {
        console.log('Transaction failure:', err);
    });
});

1 个答案:

答案 0 :(得分:1)

db.runTransaction()返回一个在事务完成时解析的promise。您需要返回此承诺(或来自您正在使用的承诺链的派生承诺)。从功能确保云功能等待工作完成。否则,您可能会观察到不可预测的结果。

return db.runTransaction(t => { ... }).then(...).catch(...)

代码中的另一个问题是doc.data是方法调用而不是属性,因此应该像这样使用:doc.data()。从技术上讲,它也是一个"快照"而不是文档,所以我要更新变量的名称,以便更清楚。