Kevin Heirich
Kevin Heirich

Reputation: 119

Mongoose update inner field

I have this kind of documents in my mongoDB :

{
   id: my_id
   inner_foo : [
      {
         inner_id : id_A
         inner_field : field_A
      },
      {
         inner_id : id_B
         inner_field : field_B
      }
   ]
}

When receiving a request, i got two ids, the id one (here my_id), and the inner_id one (here for example id_A). How can I, using JS and mongoose, update an inner field ? such as the inner_field field of one of the array contained objet using its inner_id

I think I cannot use findByIdAndUpdate since I can't make a direct reference to the correct inner_foo entry using that method, so how should I do it ?

Many thanks ! Kev.

Upvotes: 1

Views: 42

Answers (1)

Demo - https://mongoplayground.net/p/2pW4UrcVFYr

Read - https://docs.mongodb.com/manual/reference/operator/update/positional/

db.collection.update(
    { id: "my_id", "inner_foo.inner_id": "id_A" }, // find the matching document
    { $set: { "inner_foo.$.inner_field": "id_A_Update" }} // set the value on the matched array index
)

Upvotes: 4

Related Questions