nodejs Firestore突然中断:Date对象



我运行了一个简单的节点脚本来更新Firestore数据库中的数据。我几个小时前用过它,效果很好。吃了晚饭,回来了,现在我运行它时遇到了这个错误:

node ./json-to-firestore.js 

Firestore中存储的Date对象的行为将发生变化你的应用程序可能会崩溃。隐藏此警告并确保您的应用程序不要中断,您需要在之前将以下代码添加到您的应用程序调用任何其他Cloud Firestore方法:

const firestore=new firestore((;const-settings={/*your设置…*/时间戳InSnapshots:true}
firestore.settings(设置(;

错误中提供的示例不适用于我的案例。我已经在这个问题上寻求帮助,但所有的帖子似乎都是有角度的。这就是我想要做的:

var admin = require("firebase-admin");
var serviceAccount = require("./service-key.json");
const data = require("./occ-firestore.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "xxxxxxxxxxx"
});
data && Object.keys(data).forEach(key => {
const nestedContent = data[key];
if (typeof nestedContent === "object") {
Object.keys(nestedContent).forEach(docTitle => {
admin.firestore()
.collection(key)
.doc(docTitle)
.set(nestedContent[docTitle])
.then((res) => {
console.log("Document successfully written!");
})
.catch((error) => {
console.error("Error writing document: ", error);
});
});
}
});

我通过运行来执行这个脚本

node ./json-to-firestore.js

我正在运行NodeJS 8.11.3。

我查看了谷歌的文档,没有提到这种新行为。

有人能给我提个建议吗?提前感谢!

这可以这样修复:

const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
db.settings({ timestampsInSnapshots: true });

我通过将firebase版本降级到这个来解决这个问题

{
firebase-admin: "5.12.0",
firebase-functions: "1.0.1"
}

Firebase正在更改Date对象在Firestore中的存储方式。当你试图将date对象保存到Firestore:时,Bellow实际上是他们的警告(在发布这个答案的日期(

Firestore中存储的Date对象的行为将发生变化你的应用程序可能会崩溃。若要隐藏此警告并确保您的应用程序不会中断,您需要添加在调用任何其他Cloud Firestore方法之前,请将以下代码添加到您的应用程序中:

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

更重要的是,如何处理这些更改,使您的代码不会中断:

通过此更改,存储在Cloud Firestore中的时间戳将被读取为Firebase时间戳对象,而不是系统日期对象。所以你也会需要更新期望日期的代码,而不是期望时间戳。例如:

// Old:
const date = snapshot.get('created_at');
// New:
const timestamp = snapshot.get('created_at');
const date = timestamp.toDate();

最新更新