如何从Cloud Function REST API向Firestore时间戳字段存储日期?
解决Firestore时间戳转换的TypeError问题
错误原因
你遇到的TypeError: Cannot read properties of undefined (reading 'fromDate'),核心原因是当前Firebase Admin SDK版本中,Timestamp无法通过admin.firestore.Timestamp路径访问,需要使用正确的导入方式。
解决方案
直接从firebase-admin/firestore模块导入Timestamp,而非通过admin.firestore对象引用。以下是修改后的两种实现方式:
方法一(修改后)
const functions = require("firebase-functions"); const admin = require("firebase-admin"); const { Timestamp } = require("firebase-admin/firestore"); // 新增Timestamp导入 const express = require("express"); // 初始化Firebase Admin SDK(确保只初始化一次) if (!admin.apps.length) { admin.initializeApp(); } const db = admin.firestore(); // 你的API路由处理 app.post("/save-venta", (req, res) => { const idBubble = req.body.idBubble; const email = req.body.email; const nombre = req.body.nombre; const apellidos = req.body.apellidos; const total = req.body.total; const fechaCompra = req.body.fechaCompra; console.log("fechaCompra:", fechaCompra); const parsedDate = new Date(fechaCompra); console.log("parsedDate:", parsedDate); // 使用导入的Timestamp.fromMillis const timestamp = Timestamp.fromMillis(parsedDate.getTime()); console.log("timestamp:", timestamp); const promotoresRef = db.collection("promotores").doc(idBubble); const ventasData = { nombre: nombre, apellidos: apellidos, total: total, fechaCompra: timestamp, }; // 执行保存操作(示例) promotoresRef.set(ventasData, { merge: true }) .then(() => res.status(200).send("数据保存成功")) .catch(err => res.status(500).send(err.message)); });
方法二(修改后)
const functions = require("firebase-functions"); const admin = require("firebase-admin"); const { Timestamp } = require("firebase-admin/firestore"); // 新增Timestamp导入 const express = require("express"); // 初始化Firebase Admin SDK if (!admin.apps.length) { admin.initializeApp(); } const db = admin.firestore(); // 你的API路由处理 app.post("/save-venta", (req, res) => { const idBubble = req.body.idBubble; const email = req.body.email; const nombre = req.body.nombre; const apellidos = req.body.apellidos; const total = req.body.total; const fechaCompra = req.body.fechaCompra; // 使用导入的Timestamp.fromDate const fechaConvertida = Timestamp.fromDate(new Date(fechaCompra)); const promotoresRef = db.collection("promotores").doc(idBubble); const ventasData = { nombre: nombre, apellidos: apellidos, total: total, fechaCompra: fechaConvertida, }; // 执行保存操作(示例) promotoresRef.set(ventasData, { merge: true }) .then(() => res.status(200).send("数据保存成功")) .catch(err => res.status(500).send(err.message)); });
额外注意事项
- 必须确保Firebase Admin SDK只初始化一次(通过
!admin.apps.length判断),避免重复初始化报错。 - 如果使用旧版SDK(v8及以前),可以尝试
admin.firestore.Timestamp,但更推荐升级到最新SDK并使用模块化导入方式,减少兼容性问题。 - 传入的
fechaCompra是标准ISO 8601格式,new Date(fechaCompra)可以正确解析,无需额外处理。
内容的提问来源于stack exchange,提问作者Afric
相关产品推荐
相关产品推荐

