0

我有一个 Firebase Firestore 数据库,其中包含代表时间段的文档。每小时都会创建一个新文档来存储我的 IoT 传感器读数。

每个文档存储:

  • 最近的湿度
  • 最近的温度
  • 一小时内所有湿度和温度读数的数组

我不想多次收到historyMeasurements数组。是否可以观察文档中元素的更改并仅接收这些子部分的更新?还是有更好的方法来存储我的时间序列数据?谢谢!

以供参考:

在 ngOnInit 中,我有一个简单的文档 get():

import { AngularFirestore } from '@angular/fire/firestore';
import firebase from 'firebase/app';
import 'firebase/firestore';
// ...
constructor(private firestore: AngularFirestore) {
}
// ...

ngOnInit(): void {
    let docName = this.buildFormattedDateTime();            // ex: '2021_05_11_22h'

    this.firestore.collection('officePlants').doc(docName)
        .ref
        .get().then(function(doc) {
            if (doc.exists) {
                console.log("Document data:", doc.data());
            } else {
                console.log("No such document!");
            }
        }).catch(function(error) {
            console.log("Error getting document:", error);
        });
}

我的插入/更新代码:

insertData() {
    let docName = this.buildFormattedDateTime();             // example: '2021_05_12_16h'

    this.firestore.collection('officePlants').doc(docName).set({
        'humidity': this.humiditySensorReading,
        'temperature': this.temperatureSensorReading,
        'historicalMeasurements': firebase.firestore.FieldValue.arrayUnion({
            'humidity': this.humiditySensorReading,
            'temperature': this.temperatureSensorReading,
            'timestamp': firebase.firestore.Timestamp.now()
        })
    },
    {merge: true});             // 'merge: true' provides an update and creates the doc if it doesn't exist
}

示例文档:

/officePlants/2021_05_12_16h/

{ 
    humidity: 70,
    temperature: 40,
    historicalMeasurements: [
        {
            humidity: 71,
            temperature: 41,
            timestamp: 2021-05-12 11:00:00
        },
        {
            humidity: 72,
            temperature: 40,
            timestamp: 2021-05-12 11:01:00
        },
        ...
    ]
} 

我对所有选择持开放态度!

4

1 回答 1

1

是否可以观察文档中元素的更改并仅接收这些子部分的更新?

Firestore 侦听器在文档级别上运行。因此,如果文档中的某些内容发生了变化,您将收到整个文档。

如果您想接收更少的数据,请考虑在每个文档下创建一个子集合,将数据分布在多个文档中。

或者,您可以让主文档仅包含最新阅读,并history为该小时的所有历史记录提供文档。

  • 2021_05_11_22h_latest
  • 2021_05_11_22h_full
于 2021-05-12T23:41:20.203 回答