英文:
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]);
}
}
This show's changes suggested in comment below.
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论