Firestore:动态更新文档(Web)

时间:2019-12-30 12:09:38

标签: javascript firebase google-cloud-firestore

取自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数据库中,它将使用数字5更新“ people”集合中“ john”文档中名为“ field” 的字段(或更像是创建一个新字段)。要实现的目的是在“人”集合中有一个“约翰”文档,其字段名为“结果”,值为5。

我想要一个具有所有4个变量并更新特定集合中特定文档中特定字段的函数。这可能吗?有人知道解决这个问题的方法吗?

谢谢大家的回答。

1 个答案:

答案 0 :(得分:2)

您应使用square brackets notation,如下所示:

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);
});