Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - Query deeply nested Objects

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?

like image 867
relief.melone Avatar asked Sep 08 '26 16:09

relief.melone


1 Answers

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 } ] })
like image 100
mickl Avatar answered Sep 11 '26 07:09

mickl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!