[英]Firestore: Dynamically Update Document (web)
取自 Google Firebase 網站的官方指南文檔,假設我想更新一個文檔。
var washingtonRef = db.collection("cities").doc("DC");
// Set the "capital" field of the city 'DC'
return washingtonRef.update({
capital: true
})
.then(function() {
console.log("Document successfully updated!");
})
.catch(function(error) {
// The document probably doesn't exist.
console.error("Error updating document: ", error);
});
正如您所注意到的,我可以在集合括號、文檔括號和值中放置一個變量,我想分配給我的字段。 但是,我不能為字段名稱使用變量。 如果我寫這樣的東西
var collection = "people";
var document = "john";
var value = 5;
var field = "result";
var docRef= db.collection(collection).doc(document);
return docRef.update({
field: value
})
.then(function() {
console.log("Document successfully updated!");
})
.catch(function(error) {
// The document probably doesn't exist.
console.error("Error updating document: ", error);
});
,除了字段變量外,它都可以工作。 在 Firestore 數據庫中,它將更新“people”集合中的“john”文檔中名為“field”的字段(或者更像是創建一個新字段),編號為 5。我試圖實現的是擁有一個“ “people”集合中的“john”文檔,其字段名為“result”,值為 5。
我想要一個函數,它接受所有 4 個變量並更新某個集合中某個文檔中的某個字段。 這可能嗎? 有人知道解決這個問題的方法嗎?
謝謝大家的答案。
您應該使用方括號表示法,如下所示:
var collection = "people";
var document = "john";
var value = 5;
var fieldName = "result";
var obj = {};
obj[fieldName] = value;
var docRef= db.collection(collection).doc(document);
return docRef.update(obj)
.then(function() {
console.log("Document successfully updated!");
})
.catch(function(error) {
// The document probably doesn't exist.
console.error("Error updating document: ", error);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.