如何使用 Google Cloud Function 在 Firestore 上创建的文档中添加新值

问题描述 投票:0回答:1

当在我的 Firestore 上创建文档时,我想添加一个渐进计数器,例如“G0001”、“G0002”...“G0010”。我使用 Firestore API 在我的 Web 应用程序上创建此文档。我想在创建新文档并设置新字段(如

{'code': 'G0001'}
)时触发该功能。另外,我必须阅读 Firestore 的文档才能获取最后添加的代码。

示例:

在网络应用程序上正常创建的文档:

{
'name': 'Augusto',
'age': 28,
}

存储在 Firestore 上的文档已由功能更改

{
'name': 'Augusto',
'age': 28,
'code': 'G0001'
}

我用

firebase init
创建了一个节点项目,我的
index.ts
拥有它:

import * as functions from 'firebase-functions';

exports.createNewGrupoDeInsumos = functions.firestore
.document('collection-name')
.onCreate((snap,context) => {

});

ps:我不知道什么时候设置的集合名称,我认为就像上面那样。

firebase google-cloud-platform google-cloud-firestore google-cloud-functions
1个回答
1
投票

您需要在数据库中维护一个全局计数器。为此,只需创建一个文档,例如在名为

counterDocCollection
的集合下,其 id 等于
counterDocCollection
和名为
counter
的数字字段。

然后,在您的云函数中,您需要增加计数器,读取新值并使用它来生成

Gxxxx
值。

有两种方法,具体取决于该计数器的更新频率。事实上,在 Firestore 中,您大约每秒只能更新一次单个文档。所以,这两种方法是:

  1. 如果您需要更新(单个)计数器文档每秒一次,则需要使用分布式计数器。有一个专门的文档项目,请参阅 https://firebase.google.com/docs/firestore/solutions/counters
  2. 如果更新柜台单据的频率较低,可以使用
    increment
    FieldValue
    方法。另请参阅 https://firebase.google.com/docs/firestore/manage-data/add-data?authuser=0#increment_a_numeric_value

要获取计数器文件,只需使用Admin SDK即可,如下:

const counterDoc = admin.firestore().collection('counterDocCollection').doc('counterDocCollection');

要在云函数中使用

increment
方法,请执行以下操作:

import * as functions from 'firebase-functions';
//.....

const FieldValue = require('firebase-admin').firestore.FieldValue;
//.....

exports.createNewGrupoDeInsumos = functions.firestore
.document('collection-name')
.onCreate((snap,context) => {

    //.....

    const counterDoc = admin.firestore().collection('counterDocCollection').doc('counterDoc');

    return counterDoc.update({
       counter: FieldValue.increment(1);
    })
    .then(() => {
        return counterDoc.get();
    })
    .then(counterDoc => {
       const newCounterValue = doc.data().counter;

       //use newCounterValue to generate the Gxxxx value
       //Set the value of code in your initial doc

       return .....

});
© www.soinside.com 2019 - 2024. All rights reserved.