【问题标题】:Cloud Functions using wildcard path don't work使用通配符路径的 Cloud Functions 不起作用
【发布时间】:2020-07-02 08:51:12
【问题描述】:

我尝试使用云函数更新集合中的所有文档。使用此代码,它可以更新已发布问题集合中的一个文档(id 为 0):

exports.decreaseQuestionRestDuration = functions.https.onRequest((request, response) => {
   const test = admin.firestore().doc('releasedQuestions/0').update({restDuration: 42})
        .then(snapshot => {
            response.send(0)
        })
        .catch(error => {
            console.log(error)
            response.status(500).send(error)
        })
});

但是当我将使用这样的通配符路径更新集合中的所有文档时:

const test = admin.firestore().doc('releasedQuestions/{qid}').update({restDuration: 42})

它不起作用。谁能帮帮我?

我的 Cloud Firestore 结构是这样的: Cloud Firestore structure

【问题讨论】:

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


    【解决方案1】:

    您使用的通配符路径语法(即doc('releasedQuestions/{qid}'))只能在 Cloud Functions 定义中使用,例如,当您通过指定文档路径和事件类型,如下:

    exports.useWildcard = functions.firestore
        .document('users/{userId}')
        .onWrite((change, context) => {...});
    

    在您的情况下,您实际上是在调用doc() 方法,documentPath 参数应为string。这就是为什么它在第一种情况下有效,但在第二种情况下无效(您的集合中没有任何 ID 为 {qid} 的 Firestore 文档)。


    如果您想在您的 HTTP 云函数中更新集合的所有文档,您可以使用 batched write,如下所示:

    exports.decreaseQuestionRestDuration = functions.https.onRequest((request, response) => {
    
        const db = admin.firestore();
    
        db.collection('releasedQuestions').get()
            .then(snapshot => {
                let batch = db.batch();
                snapshot.forEach(doc => {
                    batch.update(doc.ref, { restDuration: 42 });
                });
                return batch.commit()
            })
            .then(() => {
                response.send(0)
            })
            .catch(error => {
                console.log(error)
                response.status(500).send(error)
            })
    
    });
    

    但请注意,批量写入最多可包含 500 个操作。因此,如果您的集合包含超过 500 个文档,您可以改用 Promise.all()


    作为旁注,值得注意的是Template literals 的存在。

    模板文字用反引号括起来(重音符号) 字符而不是双引号或单引号...并且可以包含 占位符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 2017-03-30
      • 2016-07-02
      • 1970-01-01
      • 2017-12-07
      相关资源
      最近更新 更多