Im trying to set a value of a nested array object Schema:
courses: [
{
days: [
{
courseDate: {
type: String,
},
attendance: {
type: Boolean,
},
reason: {
type: String,
},
},
],
courseId: {
type: String,
},
name: {
type: String,
},
startTime: {
type: String,
},
endTime: {
type: String,
},
},
],
Here are my attemapts:
await Student.findOneAndUpdate(
{ "courses.days._id": "6117b0c45345db20f0dc3336" },
{ $set: { "courses.$.days.$.attendance": true } },
{ new: true }
);
await Student.findOneAndUpdate(
{ "courses.days._id": req.params.dayId },
{ "courses.$[courseIndex].days.$[dayIndex].attendance": true },
{
arrayFilters: [
{
courseIndex: req.params.courseId,
},
{
dayIndex: req.params.dayId,
},
],
}
);
Here is the document:
"courses" : [
{
"_id" : ObjectId("6117b0c45345db20f0dc3330"),
"courseId" : "61155838b1fff211dd9a8765",
"name" : "succ",
"startTime" : "20:20",
"endTime" : "23:20",
"days" : [
{
"_id" : ObjectId("6117b0c45345db20f0dc3331"),
"courseDate" : "Wed Aug 04 2021 00:00:00 GMT+0300 (Israel Daylight Time)",
"attendance" : false,
"reason" : ""
},
{
"_id" : ObjectId("6117b0c45345db20f0dc3332"),
"courseDate" : "Wed Aug 11 2021 00:00:00 GMT+0300 (Israel Daylight Time)",
"attendance" : false,
"reason" : ""
},
{
"_id" : ObjectId("6117b0c45345db20f0dc3333"),
"courseDate" : "Wed Aug 18 2021 00:00:00 GMT+0300 (Israel Daylight Time)",
"attendance" : false,
"reason" : ""
},
{
"_id" : ObjectId("6117b0c45345db20f0dc3334"),
"courseDate" : "Wed Aug 25 2021 00:00:00 GMT+0300 (Israel Daylight Time)",
"attendance" : false,
"reason" : ""
}
]
},
{
"_id" : ObjectId("6117b0c45345db20f0dc3335"),
"courseId" : "61155838b1fff211dd9a8765",
"name" : "test",
"startTime" : "13:40",
"endTime" : "15:40",
"days" : [
{
"_id" : ObjectId("6117b0c45345db20f0dc3336"),
"courseDate" : "Thu Aug 05 2021 00:00:00 GMT+0300 (Israel Daylight Time)",
"attendance" : false,
"reason" : ""
},
{
"_id" : ObjectId("6117b0c45345db20f0dc3337"),
"courseDate" : "Thu Aug 12 2021 00:00:00 GMT+0300 (Israel Daylight Time)",
"attendance" : false,
"reason" : ""
},
{
"_id" : ObjectId("6117b0c45345db20f0dc3338"),
"courseDate" : "Thu Aug 19 2021 00:00:00 GMT+0300 (Israel Daylight Time)",
"attendance" : true,
"reason" : ""
},
{
"_id" : ObjectId("6117b0c45345db20f0dc3339"),
"courseDate" : "Thu Aug 26 2021 00:00:00 GMT+0300 (Israel Daylight Time)",
"attendance" : false,
"reason" : ""
}
]
}
],
The first one is throwing an Error:
Too many positional (i.e. '$') elements found in path 'courses.$.days.$.attendance'
The second one doesn't work... I don't really understand where is the issue in the second approach.
It finds the right doc but it doesn't update anything.
It's important to note that the position of every array is dynamic so the second approach is good as well.