英文:
How to query Firestore and read value as javascript Number type?
问题
我将一个数字保存到了Firestore中。然后,我尝试在云函数内部读取它,并将该值存储在一个应该是数字类型的Javascript变量中。
const doc = await db.collection('lastBlock').doc('lastBlockNumber').get();
if (doc.exists) {
lastBlockNumber = Number(doc.data());
}
我也尝试过:
if (doc.exists) {
lastBlockNumber = doc.data() as unknown as Number;
}
但是当尝试打印出lastBlockNumber的值时,我要么得到NaN,要么得到[Object object]。
这是我的数据库结构的屏幕截图:
[![在这里输入图片描述][1]][1]
[1]: https://i.stack.imgur.com/mhojz.jpg
英文:
I save a Number to Firestore. I then try to read it from within a cloud function and store the value in a Javascript variable which should be of type Number.
const doc = await db.collection('lastBlock').doc('lastBlockNumber').get();
if (doc.exists) {
lastBlockNumber = Number(doc.data());
}
I also tried:
if (doc.exists) {
lastBlockNumber = doc.data() as unknown as Number;
}
But I either get NaN or [Object object] when trying to print the value of lastBlockNumber.
答案1
得分: 1
在Firestore中,文档是一组字段。在DocumentSnapshot
上调用data()
会返回一个包含这些字段的对象。
如果您想获取特定字段,可以在快照上调用get(...)
。因此:
lastBlockNumber = doc.get("lastBlockNumber") as Number;
其中lastBlockNumber
是您想要获取的字段名称。请检查是否实际需要进行as Number
强制转换,因为Firestore可能已经以正确的类型返回该值。
英文:
A document in Firestore is a set of fields. Calling data()
on a DocumentSnapshot
gives you an object with those fields.
If you want to get a specific field, you can call get(...)
on the snapshot. So:
lastBlockNumber = doc.get("lastBlockNumber") as Number;
Where lastBlockNumber
is the name of the field you want to get. Check if the as Number
cast is actually needed here, as Firestore may already return the value as the correct type.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论