所附图片是我的 Firestore 文档中两个“日期/时间”条目的屏幕截图。
timeCompleted 是我直接在数据库中输入的值,选择“时间戳”作为字段类型。根据屏幕截图,您可以看出日期/时间以可读格式显示(这对我来说并不重要)。
timeCreated 是我的 JavaScript Reactjs 应用程序使用 firebase.firestore.Timestamp.fromDate(new Date(myDate + " " + myTime))
添加的值,按照 Google docs 的规定。与存储为时间戳类型相反,它存储为包含纳秒和秒的映射。
有没有办法将我的 JavaScript 日期 (timeCreated) 存储为真实时间戳,类似于 timeCompleted?
我的 firebase 类(通过 React 的 Context API 导入)
import app from "firebase/app";
import "firebase/firestore";
import "firebase/functions";
const config = {
apiKey: ...,
authDomain: ...,
databaseURL: ...,
projectId: ...
};
class Firebase {
constructor() {
app.initializeApp(config);
this.auth = app.auth();
this.firestore = app.firestore;
this.functions = app.functions;
}
}
export default Firebase;
我的 React 组件
import React, { useState, useEffect, useContext } from "react";
import { FirebaseContext } from "../../Firebase";
const InnerComponent = React.memo(props => {
const firebase = useContext(FirebaseContext);
//Calls Google Cloud function below
firebase.functions().httpsCallable("storeInDb")({
const myDate = "2019-02-25";
const myTime = "17:45";
orderDetails {
name: "someName",
timeCreated: firebase.firestore.Timestamp.fromDate(new Date(myDate + " " + myTime))
}
)}
我的 Google Cloud 功能
exports.storeInDb = functions.https.onCall(async (data, context) => {
return id = await orderCreation(data.orderDetails);
});
const orderCreation = async orderDetails => {
try {
const docRef = await admin.firestore()
.collection(pathToCollection...)
.add(orderDetails);
return docRef.id;
} catch (error) {
console.log("ORDER CREATION ERROR", error);
}
};
最佳答案
看起来您希望传递给可调用函数的 Timestamp 对象的类型保留在客户端和服务器之间。不幸的是,事实并非如此。当 Timestamp 对象被序列化时,它只是转换为具有秒和纳秒属性的 JavaScript 对象。另一侧的可调用函数不会自动将该对象重组为时间戳。事实上,所有类型都会丢失,所有内容都只是转换为 JSON。
您要做的就是在函数中获取该序列化对象,并在将其传递给 Firestore SDK 之前自行将其转回时间戳。然后,SDK会安排Firestore将其保存为时间戳类型字段。这意味着您必须对 data
参数进行一些初始处理,并确保它具有要写入 Firestore 的所有正确值。
同样,如果不完全清楚 - Firestore SDK 调用的对象类型必须正确。您不能传递任意对象并期望它进行智能转换。
关于javascript - 为什么我的 JavaScript 日期/时间对象在 Cloud Firestore 中存储为 map 而不是时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57066090/