How to find a specific _id and update it from an array of objects?

Viewed 29

I want to access a specific document which resides inside like:-

[
    {
        "_id": "60ebf0704c56861e10a7c69b",
        "id": "100",
        "name": "Shubham Sharma",
        "allTasks": [
            {
                "_id": "60ebf08d4c56861e10a7c6a3",
                "taskName": "Training",
                "date": "2021-07-13",
                "time": "16:04",
                "taskColor": "#ffffcc"
            },
            {
                "_id": "60ebf09e4c56861e10a7c6a7",
                "taskName": "Project",
                "date": "2021-07-15",
                "time": "15:06",
                "taskColor": "#B2D8B2"
            },
            {
                "_id": "60ebf0be4c56861e10a7c6ab",   
                "taskName": "Leave",
                "date": "2021-07-15",
                "time": "",
                "taskColor": "pink"
            },
            {
                "_id": "60ebf0d94c56861e10a7c6af",
                "taskName": "Project XYZ to be completed",
                "date": "2021-07-16",
                "time": "16:05",
                "taskColor": "#FFE4B2"
            }
        ],
        "__v": 4
    },
    {
        "_id": "60ebf07b4c56861e10a7c69f",
        "id": "200",
        "name": "Karan Srivastava",
        "allTasks": [
            {
                "_id": "60ebf0fb4c56861e10a7c6b3",
                "taskName": "Training",
                "date": "2021-07-14",
                "time": "17:06",
                "taskColor": "#B2D8B2"
            }
        ],
        "__v": 1
    }
]

I want to access a document in allTasks array by using _id of that particular allTasks document and then update the fields in it which are taskName,date,time,taskColor. How to findOneAndUpdate a specific document in allTasks array.

Suppose i want to update

"_id": "60ebf0be4c56861e10a7c6ab",   
"taskName": "Leave",
"date": "2021-07-15",
"time": "",
"taskColor": "pink"

TO

"_id": "60ebf0be4c56861e10a7c6ab",   
"taskName": "Some Task",
"date": "2021-07-16",
"time": "17:00",
"taskColor": "green"

How to do this?

1 Answers

this should work according to https://mongoosejs.com/docs/subdocs.html

const mongoose = require('mongoose')
const Parent = mongoose.model('Parent')
const { ObjectId } = mongoose.Types

const parent = await Parent.findOne({ _id: new ObjectId('60ebf0704c56861e10a7c69b') })
const child = parent.allTasks.id(new ObjectId('60ebf0be4c56861e10a7c6ab')) // this is an in memory search and doesnt hit the database, so no need for 'await'
child.set({
  taskName: 'Some Task',
  date: '2021-07-16',
  time: '17:00',
  taskColor: 'green'
})

await parent.save()
Related