Home > front end >  MongoDb findOneAndUpdate does not update specific document
MongoDb findOneAndUpdate does not update specific document

Time:08-03

I'm having trouble getting and updating the only document that matches filter in nest array of objects in mongoose, I'm using the findOneAndUpdate query in mongoose.

This is my data:

{
  "_id": "62e87e193fe01f5068f9ae11",
  "year": "2023",
  "month": "1",
  "department_id":"62e387d39ffb6ada6c590fbf",
  "blocks": [
    {
      "name": "CEEDO Schedule Block",
      "days": [
        {
          "day": 2,
          "employees": [
            {
              "employee_id":"62cf92fb3a790000170062e3",
              "schedule_type": "Day Off"
            },
            {
              "employee_id": "62cf92fb3a790000170062e2",
              "schedule_type": "Shifting"
            },
            {
              "employee_id": "62cf92fb3a790000170062e4",
              "schedule_type": "Regular"
            }
          ],
          "_id": "62e87e193fe01f5068f9ae13"
        },
        {
          "day": 6,
          "employees": [
            {
              "employee_id": "62cf92fb3a790000170062e3",
              "schedule_type": "Day Off"
            },
            {
              "employee_id": "62cf92fb3a790000170062e2",
              "schedule_type": "Shifting"
            },
            {
              "employee_id":"62cf92fb3a790000170062e4",
              "schedule_type": "Regular"
            }
          ],
          "_id": "62e87e193fe01f5068f9ae14"
        }
      ],
      "_id": "62e87e193fe01f5068f9ae12"
    }
  ]
}

And here is my query:

const update_block = await schedule_model.findOneAndUpdate({'blocks.days._id': '62e87e193fe01f5068f9ae13'}, 
    {
        $set: {"days":req.body.days, "employees":req.body.employees}
    }
    );

Thanks in advance.

CodePudding user response:

try change '62e87e193fe01f5068f9ae13' to mongoose.Types.ObjectId('62e87e193fe01f5068f9ae13')

CodePudding user response:

I finally found the answer by using the arrayFilter function in mongoose:

const update_block = await schedule_model.updateOne({
        "_id": mongoose.Types.ObjectId('62e87e193fe01f5068f9ae11')
    }, {
        "$set": {
            "blocks.$[i].days.$[j].day": 31
        }
    }, {
        arrayFilters: [{
            "i._id":mongoose.Types.ObjectId('62e87e193fe01f5068f9ae12')
        }, {
            "j._id": mongoose.Types.ObjectId('62e87e193fe01f5068f9ae14')
        }]
    })

    console.log(update_block)

Thank you.

  • Related