【问题标题】:Firestore observing and receiving sub-document instead of the whole doc? (Time series data)Firestore 观察和接收子文档而不是整个文档? (时间序列数据)
【发布时间】:2021-05-12 23:20:54
【问题描述】:

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

每个文档存储:

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

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

供参考:

在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
        },
        ...
    ]
} 

我愿意接受所有选择!

【问题讨论】:

    标签: angular firebase google-cloud-firestore observable


    【解决方案1】:

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

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

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

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

    • 2021_05_11_22h_latest
    • 2021_05_11_22h_full

    【讨论】:

    • 谢谢弗兰克,我想我需要将数据分成 2 个文档。我是时间序列数据的新手,使用 Firebase 的资源并不多
    猜你喜欢
    • 1970-01-01
    • 2019-08-12
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    相关资源
    最近更新 更多