Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/444.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Firestore:动态更新文档(web)_Javascript_Firebase_Google Cloud Firestore - Fatal编程技术网

Javascript Firestore:动态更新文档(web)

Javascript Firestore:动态更新文档(web),javascript,firebase,google-cloud-firestore,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 upd

摘自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数据库中,它将更新名为“field”的字段(或更像是创建一个新字段),该字段位于“people”集合中的“john”文档中,编号为5。我试图实现的是在“people”集合中有一个名为“result”的字段值为5的“john”文档

我想要一个函数,它接受所有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);
});
您应该使用,如下所示:

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

令人惊叹的!非常感谢你的回答,我真的很感激。太棒了!非常感谢你的回答,我真的很感激。