Update nested object by key

Hi guys, I would love your help here, as I spent 3h+ trying to solve this problem.

What I want to achieve:

  • I want to update an array inside a nested object, by having an arbitrary key

Specifically:

  • I have a variable const stringExample = "Are you a veggie?"
  • with this object:
"...: { extraFields": {
        "topic1": {
            "Are you a veggie?": {
                "email": ["e@c.com"]
            },
            "Do you like dogs?":{
                "email": ["e@c.com"]
            }
        }
    },
}
  • I want to update the “Are you a veggie?” object, by calling the the const stringExample from above
  • I want to do something like this:
documentExample.findByIdAndUpdate(
          { _id: exampleID },
          {
            $push: {
              "extraFields.topic1[$stringExample]": {
                email: "example value",
              },
            },
          }
        )

Can this be done?
Thanks!

1 Like

This is a JS question rather than mongo. It is called computed field names. See

Thanks - I actually didnt know how this was called.

I managed to get this to work in regular JS in similar use cases, but I really dont know the syntax for MongoDB to make this work & it seems to me more about how MongoDB handles nested object calls (eg. dot notation to access nested fields extraFields.topic1)

@steevej To use $push I need right now to go directly to the array email, so I need to somehow combine the dot notation of MongoDB with computed field names - something like "extraFields.topic1[stringExample]". Do you know how?

Edit: Maybe theres a better way altogether to structure this object and I am missing it.

The idea would be this I think. Feel free to replace updateOne, I just tested without any driver.

(The computed property name must point to an array)

const stringExample = "Are you a veggie?"
db.sales.updateOne(
          { _id: exampleID },
          {
            $push: {
              [`extraFields.topic1.${stringExample}.email`]: "example value",
            },
          }
        )

I think keys with spaces are not a good idea normally, but that is your choice. For example, you may camelcase it using some library.

2 Likes

@santimir It works! Many many thanks! Such a small thing, but wasnt able to figure it out.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.