node.js - 使用通配符路径的 Cloud Functions 不起作用

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

我尝试使用 Cloud Functions 更新集合中的所有文档。使用此代码,它可以更新集合中的一个文档(id 为 0)releasedQuestions:

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

最佳答案

您正在使用的通配符路径语法(即 doc('releasedQuestions/{qid}'))只能用于 Cloud Functions 定义,例如,您通过指定文档路径和事件类型来定义 Cloud Firestore 触发器,如下所示:

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

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


如果你想在你的 HTTP Cloud Functions 中更新一个集合的所有文档,你可以使用 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 的存在.

Template literals are enclosed by the backtick (grave accent) character instead of double or single quotes... and can contain placeholders.

关于node.js - 使用通配符路径的 Cloud Functions 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60787346/

相关文章:

node.js - 将 Bootstrap 和 Logo png 添加到 Apostrope CMS

node.js - 尝试添加 opencv 时 Heroku CI 构建失败,但应用程序部署有效

firebase - 如何使用Flutter更新Cloud Firestore上文档的字段?

firebase - 如何在firestore集合中生成并保证独特的值(value)?

android - 如何在Android的多模块应用程序中配置firebase

node.js - 为什么 MongoDB 中出现 UserNotFound 错误?

node.js - 从 LaunchRequest 中调用另一个 Alexa intent

javascript - 动态创建其他模块的组件

html - 如何在 Angular2 中实现 Google Analytics?

angular - 在 Angular 的 <p-column> 中用逗号而不是点显示数值