Firestore:更新嵌套对象中的字段 [英] Firestore: Update fields in nested objects
问题描述
如何更新文档嵌套对象中的字段?文档中指示了点符号,但是如何使用变量作为对象名称来实现更新?
How can one update fields in a document's nested object? The documentation indicated dot notation but how do you achieve the update with a variable as the object name?
结构类似于: collection("fruits").doc("as867f56asd")
name: "banana"
abc-variable:
description:"blah"
qty: 1
我想更新文档 as867f56asd
的 abc-variable.qty
= 2
I want to update document as867f56asd
's abc-variable.qty
= 2
我的JavaScript要求对象名称使用变量.
My JavaScript requires the use of a variable for the object name.
我无法弄清楚更新的括号符号.是否需要 .set {merge:true}
?
I can't figure out bracket notation for the update. Is .set{merge:true}
req'd?
这是我到目前为止尝试过的代码(粗略粘贴):
Here is the code I've tried so far (rough paste):
qty = evt.target.value;
//create a string
var obj = firebase.firestore.FieldPath(item).quantity;
//str = item + '.quantity';
//obj[str] = qty;
// var myUpdate = {};
// myUpdate['${item}.quantity'] = qty;
//var obj = [item]["quantity:"] = qty;
console.log("item is " + item);
//var obj = {"'" + item + "'.quantity" : qty};
//obj[item]["quantity"] = qty;
console.log("qty is " + qty);
orderRef.update (
{obj:2}
//{"quantity":qty}
//[item + '.quantity']: qty
//[`favorites.${key}.color`] = true
// ['${item}.quantity'] : qty
//[`hello.${world}`]:
//{[objname]}.value = 'value';
//['favorites.' + key + '.color']: true
//[item]["quantity"] = qty // err:reqd 2 args
//item["quantity"] = qty
//"favorites.color": "Red"
//{"`item`.quantity": qty}
//{"quantity":qty}
)
推荐答案
如果您要执行此更新:
let qty = 2
orderRef.update({"abc-variable.qty": qty});
但是如果 abc-variable
是变量的值,则可以执行以下操作:
But then where abc-variable
is the value of a variable, you would do:
let qty = 2
let variable = "abc-variable";
var values = {};
values[variable] = qty;
orderRef.update(values);
更新
此代码仅更新收藏夹:
var variableObjectName = "favorites";
var qty = Date.now(); // just so it changes every time we run
var field = {quantity:qty};
var obj = {};
obj[variableObjectName] = field;
ref.update(obj);
它不会删除文档上的任何其他属性.
It does not remove any other properties on the document.
更新2
要更新嵌套对象中的单个字段,请使用.
来寻址该字段:
To update a single field in a nested objected, use .
to address the field:
ref.update({ "favorites.quantity": Date.now() });
请参阅有关如何更新嵌套对象中字段的文档.
更新3
要对名称存储在变量中的字段执行深度更新:
To perform a deep update of a field whose name is stored in a variable:
var name = "favorites";
var update = {};
update[name+".quantity"] = Date.now();
ref.update(update);
再次显示在: https://jsbin.com/wileqo/edit?js,console
这篇关于Firestore:更新嵌套对象中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!