简体   繁体   English

Firestore:动态更新文档 (web)

[英]Firestore: Dynamically Update Document (web)

Taken from the official guide document from the Google Firebase website, let's say I want to update a document.取自 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);
});

As you notice, I could put a variable in the collection brackets, in the document brackets, and in the value, I want to assign to my field.正如您所注意到的,我可以在集合括号、文档括号和值中放置一个变量,我想分配给我的字段。 However, I cannot use a variable for the field name.但是,我不能为字段名称使用变量。 If I write something like this如果我写这样的东西

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

, it would all work except for the field variable. ,除了字段变量外,它都可以工作。 In the firestore database, it would update the field named "field" (or more like create a new one) in the "john" document in the "people" collection with number 5. What I was trying to achieve was to have a "john" document in the "people" collection with a field named "result" with a value of the number 5.在 Firestore 数据库中,它将更新“people”集合中的“john”文档中名为“field”的字段(或者更像是创建一个新字段),编号为 5。我试图实现的是拥有一个“ “people”集合中的“john”文档,其字段名为“result”,值为 5。

I want to have one function that takes all 4 variables and updates a certain field in a certain document in a certain collection.我想要一个函数,它接受所有 4 个变量并更新某个集合中某个文档中的某个字段。 Is this possible?这可能吗? Does anybody know a way around this?有人知道解决这个问题的方法吗?

Thank you all for your answers.谢谢大家的答案。

You should use the square brackets notation , as follows:您应该使用方括号表示法,如下所示:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM