使用云功能创建后更新 Firestore 文档字段

时间:2021-05-14 09:39:05

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

在我发布的应用程序的一个版本中,有一个错误会在我的集合中创建一个文档,并且在该文档的一个字段(称为“流行度”)中,该字段等于字符串“null”而不是一串数字,比如“4.5”。

导致客户端读取数据并尝试使用 Double.parseDouble("null") 时出现错误,而本应使用 Double.parseDouble("4.5")

我想添加一些云函数触发器,该触发器将侦听在该集合中创建的任何文档,并且如果创建的文档的此字段等于“null”,则将其更新为“0.0”。

我的 Firestore 构建如下:

Users (collection) -> userId (document) -> fields (Popularity, ID, Title)

我是云函数的新手,我不确定我最后是否正确使用了 .update,因为我能找到的只是 .onUpdate 的示例,而不是 .onCreate 的示例。

我尝试使用以下内容:

const functions = require('firebase-functions');

exports.createUser = functions.firestore
    .document('Users/{userId}')
    .onCreate((snap, context) => {
        const newValue = snap.data();

        const Popularity = newValue.Popularity;
      
        if (Popularity != "null") {
            return null;
        }
        
        if (Popularity == "null") {
            return snap.update({
            Popularity: "0.0"
            }, {merge: true});

        }
    });

但我的日志中出现以下错误:

TypeError: snap.update is not a function 

TypeError: snap.update is not a function 

我也尝试使用:

exports.createUser = functions.firestore
    .document('Users/{bookId}')
    .onWrite((change, context) => {
        const data = change.after.data();
        const previousData = change.before.data();

        const oldDocument = change.before.data();


        if (data.Popularity != 'null' && previousData.Popularity != 'null') {
            return null;
        }
        
        if (data.Popularity == 'null' || previousData.Popularity == 'null') {
            return change.after.ref.set({Popularity: '0.0'}, {merge: true});
        }
    });

但后来我得到了:

TypeError: Cannot read property 'Popularity' of undefined 

这里还有什么我遗漏的吗?

谢谢

1 个答案:

答案 0 :(得分:0)

看起来 type Foo<T> = { value: T } type A = { type: 'a', data: number } type B = { type: 'b', data: string } type AB = A | B // here, isA tells the TS compiler that foo is indeed a Foo<A> function isA(foo: Foo<AB>): foo is Foo<A> { return foo.value.type === 'a' } // same here for Foo<B> function isB(foo: Foo<AB>): foo is Foo<B> { return foo.value.type === 'b' } function doStuff(foo: Foo<AB>) { if(isA(foo)) { // it works ! here TS recognise foo as Foo<A> return doStuffA(foo) } else if(isB(foo)) { // same here, TS knows that foo is a Foo<B> return doStuffB(foo) } } function doStuffA(foo: Foo<A>) { // ... } function doStuffB(foo: Foo<B>) { // ... } 是一个 DocumentSnapshot object,它(如果您查看其文档)确实没有 snap 方法。要更新快照来自的文档,您需要调用 update()