如何在Firestore函数中使用Type模型获取字段值

huangapple go评论76阅读模式
英文:

How to use Type Model on Firestore Function to get Field Value

问题

I'm getting my data from firestore and I can print doc.data and it gives me an object with the list of values from the collection, one of which is unixtime.

Problem: I can't print only the specific value of unixtime, it comes through as undefined so I'm trying to figure out how to apply my type model correctly so I can console log the value of unixtime. What am I doing wrong with my type model implementation? How do I print only the value of unixtime? 1st photo is the data in firestore, 2nd photo is doc.data printing in console.log cloud function. 3rd photo is if I add myVar2 to the end of doc.data, it says "doc.data undefined".

英文:

I'm getting my data from firestore and I can print doc.data and it gives me an object with the list of values from the collection, one of which is unixtime.

Problem: I can't print only the specific value of unixtime, it comes through as undefined so I'm trying to figure out how to apply my type model correctly so I can console log the value of unixtime. What am I doing wrong with my type model implementation? How do I print only the value of unixtime? 1st photo is the data in firestore, 2nd photo is doc.data printing in console.log cloud function. 3rd photo is if I add myVar2 to the end of doc.data, it says "doc.data undefined".

import { firestore } from 'firebase-admin';

export default async () => {
  const FirestoreInstance = firestore();
  const getunixtime = FirestoreInstance.collection('2023WNS').doc('uDIP3FvGg2bxDbBusJ9cq4iIyec2');
  const doc = await getunixtime.get();

  type ObjectKey2 = keyof typeof doc.data;
  const myVar2 = 'unixtime' as ObjectKey2;

  if (!doc.exists) {
    console.log('No such document!');
  } else {
    console.log('Document data:', doc.data[myVar2]);
  }
}

如何在Firestore函数中使用Type模型获取字段值

如何在Firestore函数中使用Type模型获取字段值

如何在Firestore函数中使用Type模型获取字段值

This show's changes suggested in comment below.

如何在Firestore函数中使用Type模型获取字段值

答案1

得分: 1

doc.data() 是一个返回对象而不是属性的函数。你只需要这样做:

const data = doc.data();
const unixtime = data.unixtime;

这与 TypeScript 或类型信息无关。你只是没有调用 data 方法来获取文档数据。

英文:

doc.data() is a function that returns an object, not a property. All you need to do is this:

const data = doc.data();
const unixtime = data.unixtime;

This has nothing to do with TypeScript or typing information. You're just not calling the data method to get the document data.

huangapple
  • 本文由 发表于 2023年5月21日 06:09:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76297532.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定