Reputation: 18585
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?
Structure is like: collection("fruits").doc("as867f56asd")
name: "banana"
abc-variable:
description:"blah"
qty: 1
I want to update document as867f56asd
's abc-variable.qty
= 2
My JavaScript requires the use of a variable for the object name.
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}
)
Upvotes: 3
Views: 4458
Reputation: 600071
If the update you're trying to do:
let qty = 2
orderRef.update({"abc-variable.qty": qty});
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);
Update
This code updates only the favorites:
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.
Update 2
To update a single field in a nested objected, use .
to address the field:
ref.update({ "favorites.quantity": Date.now() });
See the documentation on how to update fields in nested objects.
Update 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);
Once again shown in: https://jsbin.com/wileqo/edit?js,console
Upvotes: 13