I'm trying to get study materials related to a subject from 'study material' collection when subject name from 'subject' collection is passed.
router.get('/materials',(req,res) =>{
Materials.find({"subjectName":"Physics"}).exec((err,materials) =>{
if(err){
return res.status(400).json({
error:err
});
}
return res.status(200).json({
success:true,
existingMaterials:materials
});
});
});
This is what I have got so far.How to pass subject name as a variable?
I did the react part this way. Is this correct?
export default class ViewSubjectMaterial extends Component {
constructor(props){
super(props);
this.state={
materials:[]
};
}
componentDidMount(){
this.retrieveMaterials();
}
retrieveMaterials(){
axios.get("http://localhost:8000/materials?subjectName=Physics").then(res =>{
if(res.data.success){
this.setState({
materials:res.data.existingMaterials
});
console.log(this.state.materials)
}
})
}}
Do you need something like this?
router.get('/materials',(req,res) =>{
const subjectName = req.query.subjectName;
Materials.find({"subjectName":subjectName}).exec((err,materials) =>{
if(err){
return res.status(400).json({
error:err
});
}
return res.status(200).json({
success:true,
existingMaterials:materials
});
});
});
Then, you will have to send this in the request query. for example:
GET http://localhost:8000/materials?subjectName=Physics
change get to post method
router.post('/materials',(req,res) =>{
/// {subjectName:"Physics",curriculum:"Intro"} example of req.body
Materials.find(req.body).exec((err,materials) =>{
if(err){
return res.status(400).json({
error:err
});
}
return res.status(200).json({
success:true,
existingMaterials:materials
});
});
});
add these lines in index js where express defined
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());