【问题标题】:How to handle a read and write in Cloud Functions Firestore如何在 Cloud Functions Firestore 中处理读取和写入
【发布时间】:2017-10-19 00:59:06
【问题描述】:

我对如何重构代码以在没有嵌套承诺的情况下进行读写有点困惑。在编写一个对象时,如果该对象设置了一个标志,我想用新的计数更新它的“相关”对象。我有两个问题。

1) 从读取到写入的嵌套 Promise。 2) 我应该返回什么

exports.updateRelationshipCounts = functions.firestore
    .document('masterProduct/{nfCode}').onWrite((event) => {

    //on writing of record:

    var newProduct = event.data.data();
    if (newProduct.isGlutenFreeYN === 'Y') {
        console.log('Gluten Free');

        //Update GF count in the Brand Object:

        var db = admin.firestore();
        var docRef = db.collection("masterBrand").doc(newProduct.brandNFCode);
        var doc = docRef.get()
            .then(doc => {

                doc.glutenFreeCount = doc.glutenFreeCount + 1


                docRef.set(newProduct.brand)
                    .then(function () {
                        console.log("Document successfully written!");
                    })
                    .catch(function (error) {
                        console.error("Error writing document: ", error);
                    });

                })
            .catch(err => {
                    console.log('Error getting document', err);
            })
    };

});

此外,它还希望我返回一些东西……无?

【问题讨论】:

  • 谁要你退货? .onWrite() 事件处理程序? doc here 中的 .onWrite() 处理程序均未显示任何返回的内容。

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


【解决方案1】:

您可以使用链接并消除一些嵌套。

exports.updateRelationshipCounts = functions.firestore
  .document('masterProduct/{nfCode}').onWrite((event) => {
    //on writing of record:
    var newProduct = event.data.data();
    if (newProduct.isGlutenFreeYN === 'Y') {
        console.log('Gluten Free');
        //Update GF count in the Brand Object:

        var db = admin.firestore();
        var docRef = db.collection("masterBrand").doc(newProduct.brandNFCode);
        docRef.get().then(doc => {
            doc.glutenFreeCount = doc.glutenFreeCount + 1
            return docRef.set(newProduct.brand);
        }).then(() => {
            console.log("document successfully written);
        }).catch(err => {
            // will log all errors in one place
            console.log(err);
        });
    }
});

变化:

  1. 链在顶层而不是越来越深的嵌套。
  2. 返回嵌套的 Promise,以便它们正确链接。
  3. 将错误处理程序合并到一个.catch()

【讨论】:

    猜你喜欢
    • 2020-07-05
    • 2017-08-15
    • 2018-04-04
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2018-03-23
    • 2021-09-25
    相关资源
    最近更新 更多