Firebase云函数 - 更改Firestore设置

8

我正在使用Firebase云函数,最近日志显示了这个消息:

The behavior for Date objects stored in Firestore is going to change AND YOUR APP MAY BREAK. To hide this warning and ensure your app does not break, you need to add the following code to your app before calling any other Cloud Firestore methods:

const firestore = new Firestore();
const settings = {/* your settings... */ timestampsInSnapshots: true};
firestore.settings(settings);
问题在于,当我将那段代码添加到我的函数文件中时,每次尝试部署时都会出现这个错误:
ReferenceError: Firestore is not defined

有人能帮我找出问题所在吗?

(即使我已经使用Firestore功能,我是否需要在package.json文件中添加Firestore依赖项?)

谢谢

4个回答

7
这应该可以起作用:
const admin = require('firebase-admin');
admin.initializeApp();

const firestore = admin.firestore();

// Add this magical line of code:
firestore.settings({ timestampsInSnapshots: true }); 

然后在您的函数中直接使用firestore对象:

firestore.doc(`/mycollection/${id}`).set({ it: 'works' })

2019年3月更新:

如果使用的是firebase-admin 7.0.0或更高版本,则无需进行此修复。

firebase-admin2019年1月31日发布的7.0.0版本中,引入了一些重大变化

BREAKING:timestampsInSnapshots默认值已更改为true。

现在默认启用timestampsInSnapshots设置,因此从DocumentSnapshot读取的时间戳字段将返回Timestamp对象,而不是Date。任何期望收到Date对象的代码都必须进行更新。

此外,正如官方文档所述,timestampsInSnapshots将在未来的版本中被删除,因此请确保完全删除它。


@Valentin 很高兴听到这个消息。愉快的编程 :)) - Yulian
@Valentin请注意,在7.0.0版本发布后,有一些重大变更。我已相应地更新了我的答案。 - Yulian

4
您在日志中得到的建议是针对直接使用Firestore节点SDK的人。然而,当通过Cloud Functions编写Firestore触发器时,Admin SDK会自动初始化,进而自动初始化Firestore SDK。因此,您没有机会自己初始化它。
在Firestore SDK完全定稿之前,您唯一能做的就是确保您对日期的使用与未来完全发布的Firestore SDK一致。这意味着在从快照中读取日期时应使用Timestamp对象。如果您正在执行此操作,则可以忽略此警告消息。

1
哎呀。如果我这样做,就会出现这个错误:foo.dateTimeCreated.toDate不是一个函数。 - Valentin
您是否可以单独提出一个问题,并提供一个完整且最小化的代码示例,以及您试图阅读的所有文档? - Doug Stevenson

1

请检查如何初始化您的Firebase应用程序,在我的情况下,我将其称为firebase,因此我使用以下内容:

const firestore = firebase.firestore();
const settings = {/* your settings... */     timestampsInSnapshots: true};
firestore.settings(settings);

这不会起作用,因为Cloud Functions和Admin SDK直接初始化Firestore SDK(在使用Firestore触发器时),而您没有机会更改其工作方式。有关更多详细信息,请参见我的答案。 - Doug Stevenson

1
这是在Firebase云函数中正确的操作方式:
import * as admin from 'firebase-admin';


admin.initializeApp();
const settings = { timestampsInSnapshots: true };
admin.firestore().settings(settings);

上面的代码是用typescript编写的


谢谢Joel!这对TypeScript很有帮助 :) - Mittal Patel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接