Search code examples
node.jsdatabasemongodbmongoosenested-object

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?


Solution

  • 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 } ] })