4Manuals

  • PDF Cloud HOME

Firestore:动态更新文档(Web) Download

    CSS / JS-如何覆盖一个孩子而不是其他孩子的父母过渡 反应:更改方向后触发重新渲染和offsetWidth的重新计算 我的Javascript从'string'转换为'integer'或'number'无效 如何删除外部索引并合并内部json 在React Native 图片无法通过javascript刷新 如何在react图表上的datakey中操作DateTime 在Cypress中保存变量 如何从作为请求传递的输入类型数据绑定中提取数据 通过dropzone laravel通过电子邮件发送多个图像

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



Similar searches
    Fluentd在工作,但在elastcisearch上未创建索引 如何在mysql中解密密码? 就绪的API自动化框架 存储过程;子查询返回的值超过1。当子查询遵循=,!=,<,<=,>,> =时,不允许这样做 使用原子快照对象的弱计数​​器的免等待实现