Firebase Firestore动态数据请求

hxzsmxv2  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(142)

我想从firebase中获取并设置一些当前月份的数据。

const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]

const date = new Date()
const currentMonth = monthNames[date.getMonth()] 

location.airTemp = doc.data().currentMonth.airTemp

在数据库中,每个位置都有一个月对象..即April:{airTemp:34 },May:{ airTemp:32 }等
如果我只是用一个特定的月份替换currentMonth,它就可以工作,但不是动态的。有没有办法解决这个问题?

but5z9lq

but5z9lq1#

您应该使用方括号notation,如下所示:

var db = firebase.firestore()

    db.collection('Collection_Id').doc('Doc_Id').get().then(function (doc) {
        if (doc.exists) {
            const monthNames = ["January", "February", "March", "April", "May", "June",
                "July", "August", "September", "October", "November", "December"]

            const date = new Date()
            const currentMonth = monthNames[date.getMonth()]
            location.airTemp = doc.data()[currentMonth].airTemp

        } else {
            // doc.data() will be undefined in this case
            console.log("No such document!")
        }
    });

相关问题