[英]How to update collection documents in firebase in flutter?
我想更新文檔字段,我嘗試了以下代碼,但它沒有更新。
任何人都可以給我一個解決方案嗎?
我的代碼:
var snapshots = _firestore
.collection('profile')
.document(currentUserID)
.collection('posts')
.snapshots();
await snapshots.forEach((snapshot) async {
List<DocumentSnapshot> documents = snapshot.documents;
for (var document in documents) {
await document.data.update(
'writer',
(name) {
name = this.name;
return name;
},
);
print(document.data['writer']);
//it prints the updated data here but when i look to firebase database
//nothing updates !
}
});
對於這種情況,我總是建議遵循文檔中的確切類型,以查看可用的選項。 例如, DocumentSnapshot
對象的data
屬性是Map<String, dynamic>
。 當您對此調用update()
時,您只是在更新文檔的內存表示,而不是實際更新數據庫中的數據。
要更新數據庫中的文檔,您需要調用DocumentReference.updateData
方法。 並且要從DocumentSnapshot
到DocumentReference
,您可以調用DocumentSnapshot.reference
屬性。
所以像:
document.reference.updateData(<String, dynamic>{
name: this.name
});
與此無關,您的代碼看起來有點不習慣。 我建議使用getDocuments
而不是snapshots()
,因為后者可能會導致無限循環。
var snapshots = _firestore
.collection('profile')
.document(currentUserID)
.collection('posts')
.getDocuments();
await snapshots.forEach((document) async {
document.reference.updateData(<String, dynamic>{
name: this.name
});
})
這里的區別在於getDocuments()
讀取數據一次,然后返回它,而snapshots()
將開始觀察文檔,並在發生更改時(包括更新名稱時)將它們傳遞給我們。
API 中發生了很多變化,例如Firestore
被FirebaseFirestore
取代, doc
is in 等。
更新文檔
var collection = FirebaseFirestore.instance.collection('collection'); collection .doc('some_id') // <-- Doc ID where data should be updated. .update({'key' : 'value'}) // <-- Updated data .then((_) => print('Updated')) .catchError((error) => print('Update failed: $error'));
更新文檔中的嵌套值:
var collection = FirebaseFirestore.instance.collection('collection'); collection .doc('some_id') // <-- Doc ID where data should be updated. .update({'key.foo.bar' : 'nested_value'}) // <-- Nested value .then((_) => print('Updated')) .catchError((error) => print('Update failed: $error'));
要在不覆蓋整個文檔的情況下更新文檔的某些字段,請使用以下特定於語言的
update()
方法:
final washingtonRef = FirebaseFirestore.instance.collection("cites").doc("DC");
washingtonRef.update({"capital": true}).then(
(value) => print("DocumentSnapshot successfully updated!"),
onError: (e) => print("Error updating document $e"));
您可以將文檔中的字段設置為服務器時間戳,用於跟蹤服務器何時收到更新。
final docRef = FirebaseFirestore.instance.collection("objects").doc("some-id");
final updates = <String, dynamic>{
"timestamp": FieldValue.serverTimestamp(),
};
docRef.update(updates).then(
(value) => print("DocumentSnapshot successfully updated!"),
onError: (e) => print("Error updating document $e"));
如果您的文檔包含嵌套對象,您可以在調用 update() 時使用“點符號”來引用文檔中的嵌套字段:
// Assume the document contains:
// {
// name: "Frank",
// favorites: { food: "Pizza", color: "Blue", subject: "recess" }
// age: 12
// }
FirebaseFirestore.instance
.collection("users")
.doc("frank")
.update({"age": 13, "favorites.color": "Red"});
如果您的文檔包含數組字段,您可以使用 arrayUnion() 和 arrayRemove() 添加和刪除元素。 arrayUnion() 將元素添加到數組,但僅添加不存在的元素。 arrayRemove() 刪除每個給定元素的所有實例。
final washingtonRef = FirebaseFirestore.instance.collection("cities").doc("DC");
// Atomically add a new region to the "regions" array field.
washingtonRef.update({
"regions": FieldValue.arrayUnion(["greater_virginia"]),
});
// Atomically remove a region from the "regions" array field.
washingtonRef.update({
"regions": FieldValue.arrayRemove(["east_coast"]),
});
您可以增加或減少數字字段值,如以下示例所示。 增量操作將字段的當前值增加或減少給定的數量。
var washingtonRef = FirebaseFirestore.instance.collection('cities').doc('DC');
// Atomically increment the population of the city by 50.
washingtonRef.update(
{"population": FieldValue.increment(50)},
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.