3

I currently have a problem where I have to update entries in a deeply nested Document. Now to simplify my problem I have this example. Let's assume I store cars in my MongoDB. A Document would look like this

{
  Make: "BMW",
  Model: "3Series",
  Wheels: [
    {
      _id: someObjectId
      Size: "19 inch",
      Screws: [
        {
          _id: someObjectId
          Type : "M15x40"
        },
        {
          _id: someObjectId
          Type : "M15x40"
        }
      ]
    }
  ]
}

Now if I want to update a specific Wheel, my code would look somewhat like this

CarModel.findOneAndUpdate({
  "_id": CarId, "Wheels._id": WheelId
}, {
  "$set" : {
    "Wheels.$.Size": NewSize
  }
})

Now this works. But I am pretty lost on how I would update an specific screw as I am going through 2 Arrays. Any Idea how I could make this work?

1 Answer 1

2

You need arrayFilters functionality to define the path for more than one nested array:

CarModel.findOneAndUpdate(
    { "_id": CarId },
    { $set: { "Wheels.$[wheel].Screws.$[screw].Type": "something" } },
    { arrayFilters: [ { 'wheel._id': WheelId }, { 'screw._id': screwId } ] })
Sign up to request clarification or add additional context in comments.

16 Comments

nice. That looks cleaner also for the already working use case. I'll try it out immediately. Thanks ;) Is it possible that the mongoose documentation is pretty incomplete on that topic or am I just unable to find this?
Ok. I will have to figure out how to use it with TypeScript as it is missing in their types as by the looks of it. Will come back to this ;)
@relief.melone not sure if you can find it in mongoose documentation, it's just MongoDB syntax and mongoose as ODM will send it directly to the database
hmmm. I keep getting cannot use the part (Wheels Wheels.$[wheel].Screws... to traverse the element. Aslo weird that the @types/mongoose don't include arrayFilters in their QueryFindOneAndUpdateOptions interface
Alright. So I updated the DB to V4.0 and see there. It works as a charm. So I marked the answer as accepted again and for anyone who Is having the same issues. Make sure you have at least MongoDB V3.6. Thanks again
|

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.