我有一个 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
},
...
]
}
我对所有选择持开放态度!