I am finding data from an array. that is a course and I want to find out an article by using the title, which is stored into the Course's Articles. I am going step by step... (1) I want fine the course by the name, (2) after of it, I want to find an article into course's article by using the title of an article (3) and render the article and course to the web page here is code
const course = req.params.course
const article_title = req.query.article
Course.findOne({name: course , article:article_title}).then(function(data){
console.log(data)
res.render('article',{data :data})
}).catch((err)=>{console.log(err)});
here is DB
_id:61c057cfd70f2fb178d4e996
name:"Soft "
discription:"House"
article:Array
0:Object
title:"Where does it come from?"
content:"<p>Title is very important for an article to explain content | article..."
_id:61c05d4a3905f61f72a8e61b
1 :Object
2:Object
CodePudding user response:
To search you can use:
Couse.findOne({name: course, 'article.title': article_title})
So you will get the document with the articles you need.
Using projection and $elemMatch
, you can filter the article array itself so that only the subdocument you want is there:
Couse.findOne({name: course, 'article.title': article_title}, {
article: {
$elemMatch: {
title: article_title
}
}
})
You can try it in MongoPlayground https://mongoplayground.net/p/SVXNGE6tuW7