如何使用firebase-admin在Firestore中将日期保存为时间戳?

5

尝试将JavaScript日期转换为Firestore时间戳时会引发错误

TypeError: Cannot read property 'Timestamp' of undefined

我尝试了两种方法:

  1. 使用firebase-admin
const admin = require('firebase-admin');
const db = admin.firestore();
const timestamp = db.Timestamp.fromDate(new Date(date));
  1. 使用 firebase.firestore:
const firebase = require('firebase');
const timestamp = firebase.firestore.Timestamp.fromDate(new Date(date));

日期在使用new Date时,格式应为"2017-01-29"。

期望结果: firestore时间戳。

实际结果: 类型错误:无法读取未定义的属性“Timestamp”

注意: db和firebase都不是null或undefined。

有没有一种确定的方法从javascript日期对象创建firestore时间戳?

3个回答

12

你的第二个例子根本没有使用 Firebase Admin SDK - 那是 Firebase web client SDK。

如果你在 v11 之前使用 Admin SDK:

const admin = require('firebase-admin');
const timestamp = admin.firestore.Timestamp.fromDate(...)

或者v11:

const { Timestamp } = require('firebase-admin/firestore')
const timestamp = Timestamp.fromDate(...)

我将我的第一个选项更改为admin.firstore.Timestamp.fromDate(new Date(date)),现在它可以正常运行。 - J.D
3
这个程序是在部署的云函数上运行的,有没有办法让它在本地测试云函数时也能工作?它返回 TypeError: Cannot read properties of undefined (reading 'fromDate')。 - Ilker Baltaci

5

接受的答案在最新版本的firebase-admin(v11)中不起作用。admin.firestore.Timestamp未定义。以下是我在新版本中使其工作的方法:

const { Timestamp } = require('firebase-admin/firestore')
const timestamp = Timestamp.fromDate(new Date(...))

-3

导入

import * as firebase from 'firebase/app';

并使用

created_at = firebase.firestore.FieldValue.serverTimestamp();   

1
这对于 Firebase Admin Sdk 来说是不相关的。 - John Yepthomi

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