3

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}
)
6
  • Hey Ron. Can you show the code that you tried? I think yuo're looking for something like values[abc-variable+".qty"] = 2, but it's easier to answer if I see what you've done already. Commented Sep 8, 2018 at 1:06
  • inside the .update( IDE says values is not defined. If I wrap it in {} it says Unexpected token [. If I declare values = {} prior to the update, the IDE takes it and it passes linting but browser console throws error Uncaught TypeError: Cannot read property 'quantity' of undefined Doing: orderRef.update (values[item+".quantity"] = qty) Commented Sep 8, 2018 at 1:16
  • @FrankvanPuffelen It seems like I would need to nail a type of reference to the field (which is an object) and then from there, update a specific property. FieldPath or even defining a reference using URLencoding \fruits\abc-123doc\obj-field-var but I can't figure it out. I bout to give up and just re-write the whole document to update a single field. I know that works... Commented Sep 8, 2018 at 1:23
  • This myUpdate['${item}.quantity'] = qty; should probably be myUpdate[`${item}.quantity`] = qty;. So with backticks around the string, since that's the JavaScript syntax for string interpolation. Commented Sep 8, 2018 at 4:36
  • What is item in the code you provided? Commented Sep 8, 2018 at 4:38

1 Answer 1

13

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

Sign up to request clarification or add additional context in comments.

6 Comments

I challenge you to try to .update a single field of an object stored in a Firestore document where a variable is used as the stored object's name. If you can do it, I'll mail you [anyone] a free hightechtele.com BIC lighter. srsly.
I sincerely appreciate the help. Notice how the other object properties are deleted after the .update? See updated jsbin -> jsbin.com/decizubuyi/edit?js,console ...could u make this work, just want to update quantity property only and leave other properties alone.
Sorry Ron, I can't reproduce what you're saying. The only time my entire document was overwritten was when you called ref.set() in your code. Once I updated your code in jsbin.com/xibodoc/1/edit?js,console to remove the set() it maintains all other fields, no matter how often I call update().
not the entire document, the entire nested object. Updating a single property of a nested object (without having the other nested object's properties deleted) is the issue/problem. Notice the document in my jsbin included a nested object with 2 properties, name and quantity. Yours shows a nested object with a single property.
Ah, I get it now. That quite simple: ref.update({ "favorites.quantity ": Date.now() }). See the documentation on how to update fields in nested objects.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.