如何查询Firestore并将值读取为JavaScript Number类型?

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

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.

Here is a screenshot of my DB structure:
如何查询Firestore并将值读取为JavaScript Number类型?

答案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.

huangapple
  • 本文由 发表于 2023年7月6日 14:31:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76626067.html
匿名

发表评论

匿名网友

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

确定