【问题标题】:Mongodb-How to pass collection field as a variable to get data from another collection?Mongodb-如何将集合字段作为变量传递以从另一个集合中获取数据?
【发布时间】:2021-11-08 02:43:54
【问题描述】:

当“主题”集合中的主题名称通过时,我正在尝试从“学习材料”集合中获取与某个主题相关的学习材料。

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
        });
    });
});

这是我目前得到的。如何将主题名称作为变量传递?

我以这种方式完成了反应部分。这是正确的吗?

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)
          }
        })
      }}

【问题讨论】:

  • 请提供您的材料样本数据
  • subjectName=Physics,curriculum=Intro to Matter,topic=What is matter?,notes=Matter notes 1. 类似的东西

标签: javascript node.js arrays reactjs mongodb


【解决方案1】:

你需要这样的东西吗?

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
    });
});
});

然后,您必须在请求查询中发送它。例如:

GET http://localhost:8000/materials?subjectName=Physics

【讨论】:

  • GET http://localhost:8000/materials?subjectName=Physics 请告诉我如何在 react 中编写代码。
  • 你应该使用一个库来处理 http 请求,比如说 node-fetch npmjs.com/package/node-fetch 然后你用这个库执行一个 GET 请求
【解决方案2】:

更改 get 到 post 方法

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
    });
});
});

在明确定义的索引js中添加这些行

app.use(bodyParser.urlencoded());

app.use(bodyParser.json());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-14
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    相关资源
    最近更新 更多