Home > Enterprise >  How can I get the data of student by searching specific field?
How can I get the data of student by searching specific field?

Time:10-22

I want to get the data of a student using a specific field in my schema, so I have this search button in the front end wherein if the user types the student number, it will render its information...

By the way, I'm mapping the data since I'm all the products

When I tried to console.log it, I'm receiving a null value.. I can't connect the search studentid in the frontend and in the backend

enter image description here

const MyProducts = () => {
  const [buyerId, setBuyerId] = useState()

  const getBuyerData = async () =>{
      const res = await publicRequest.get(`/users/studentId`,buyerId)
      console.log(res.data)

    return (
                            

    <Box sx={{display: 'flex',gap: '10px'}}>
         <TextField onChange={(e) => setBuyerId(e.target.value)} placeholder="e.g, 2022304827" fullWidth multiline label="Input Student Number" />
         <Button color="secondary" onClick={getBuyerData} variant="contained" size="small">Search</Button>
     </Box>
                            
)}}

router.js

router.get('/studentId', getUserByStudentId)

controller.js

export const getUserByStudentId = async (req,res) =>{
    const {studentid} = req.body
   try {
    const user = await User.findOne({studentid:studentid})
    res.status(200).json(user)
   } catch (error) {
    res.status(400).json({message: error.message})
   }
}

UserSchema

const UserSchema = mongoose.Schema({
    username: {type: String, unique: true, required: true},
    password: {type: String,  required: true},
    email: {type: String,  unique: true, required: true},
    studentid: {type: String, unique: true, required: true},
    isAdmin:{type: Boolean, default: false},
},
{ timestamps: { createdAt: true } }
)

export default mongoose.model('User', UserSchema)

So when I used, Postman, I can get the data..

enter image description here

CodePudding user response:

You are doing GET request, but sending request body. Try to send the data as a URL param, like this:

Router:

router.get('/studentId/:id', getUserByStudentId);

Controller:

export const getUserByStudentId = async (req,res) =>{
   const { id } = req.params;
   try {
    const user = await User.findOne({ studentid: id })
    res.status(200).json(user)
   } catch (error) {
    res.status(400).json({message: error.message})
   }
}

Client:

const res = await publicRequest.get(`/users/studentId/${buyerId}`)
  • Related