我有带时间戳的 Firestore 数据。
用户将数据备份为 JSON 文件 - 导出功能
const dataStr = JSON.stringify(todos);
let dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr);
let fileName = 'data.json';
let linkElement = document.createElement('a') as HTMLAnchorElement;
linkElement.setAttribute('href', dataUri);
linkElement.setAttribute('download', fileName);
linkElement.click();
Then User will restore data- Import-Function
const uploadFile = fileInput.files[0];
const fileReader = new FileReader();
fileReader.onload = async (e) => {
const dataStr = e.target?.result as string;
const newDatas = JSON.parse(dataStr) as todosProps[];
console.log(newDatas);
settodos([
...todos,
...newDatas
]);
try {
newDatas.map(async (d) => {
await setDoc(doc(collectionRef, d.id.toString()), {
...d,
});
});
console.log('finish import');
} catch (error) {
console.error(error);
}
我注意到,firestore 时间戳对象值在转换为 JSON 时具有不同的构造方法。
所以我不能在导入的函数中使用像“.toDate().toMillis”这样的 firestore 函数。那么为什么它与原始时间戳不同。可能是我将原始数据转换为 JSON 。还是我的代码错了?
我不知道尝试。我期待得到正确的订单。
学分@Rahul Kumar
对于任何拥有 toDate() is not a function 错误的人来说,可能是因为您在 JSON 对象上使用它。您可以简单地使用从 firebase 收到的时间戳对象,或者如果您不能直接使用它,那么要将它转换回时间戳对象,您可以这样做:
const timestamp = new firebase.firestore.Timestamp(jsonTimestamp.seconds, jsonTimestamp.nanoseconds)
现在做 timestamp.toDate() 会起作用