Reputation: 55
I have some complex object model looks like this :
courses: [
{
"name": "Linux",
"slug": "linux",
"_id": "123213123123",
"sections": [
{
"name" : "section1",
"_id": "123123123",
"lessons": [
{
"title": "lesson1"
"content": "some content"
}
]
},
{
"name" : "section2",
"_id": "1231231444",
"lessons": [
{
"title": "lesson1"
"content": "some content"
}
]
}
]
}
]
I'm trying to push to specific section lessons with $push without success,
My code:
const updatedCourse = await Course.findOneAndUpdate(
{ slug: courseSlug },
{
$push: {
'sections.lessons': { title, content, free_preview, video: videoKey },
},
},
{ new: true, useFindAndModify: false }
);
Need help with mongoose expression to find section by id and push to lessons array, thanks .
Upvotes: 1
Views: 1445
Reputation: 521
Following code can help you , I have tried at my local, it is working fine
const updatedCourse = await Course.findOneAndUpdate((
{ slug: courseSlug },
{
$push: {
'sections.$[el].lessons': { title, content , free_preview , video },
},
},
{
arrayFilters:[{
"el._id":"1231231444"
}]
}
)
After running above query the output is as below, the sections with _id having 1231231444 have a new lesson
{
"name": "Linux",
"slug": "linux",
"sections": [{
"name": "section1",
"_id": "123123123",
"lessons": [{
"title": "lesson1",
"content": "some content"
}]
}, {
"name": "section2",
"_id": "1231231444",
"lessons": [{
"title": "lesson1",
"content": "some content"
}, {
"title": "title",
"content": "content",
"free_preview": false,
"video": "123"
}]
}]
}
Upvotes: 1