Search code examples
javascriptmongodbmongoosejavascript-objects

Is it possible to update a value contained in an object


My data base actually looks like that :

{
  object1: {
    object2: {
      enabled: false,
      string: "foo"
    },
    object3: {
      enabled: true,
      string: "bar"
    }
  }
}

I wanna update the enabled: of the object2 without changing the "foo" value.

I tried this:

data.updateOne({ object1: { object2: { enabled: true } } });

but it change all the object2, it delete the object3 and delete the string value of the object2. How can i update my database without change it totally?


Solution

  • You should use the dot notation:

    To specify a < field > in an embedded document or in an array, use dot notation.

    data.updateOne({ query }, { $set: { "object1.object2.enabled": true } });