Writing a GET request for multiple property searching in mongodb (React, Node.js)

Advertisements

I’ve been trying to make use of db.collections.find function in my node.js react application, which is about searching and hiring teachers to learn a certain subject. What I want to do is present a user with 3 select boxes. One for the teacher’s location, second for the teacher’s subject (math, literature, etc.), and the third one for the types of people a teacher works with (school students or university students). The user chooses the options he wants and on the right side of the screen teachers with the chosen properties appear.
This is how the searchbox looks right now:

const Main = () => {
    const [subject, setSubject] = useState('');
    const [status, setStatus] = useState('');
    const [district, setDistrict] = useState('');


    const handleChange1 = (event) => {
        setSubject(event.target.value);
        console.log("new subject: ", event.target.value)
    };

    const handleChange2 = (event) => {
        setStatus(event.target.value);
        console.log("new status: ", event.target.value)
    };

    const handleChange3 = (event) => {
        setDistrict(event.target.value);
        console.log("new district: ", event.target.value)
    };

    return (
        <div className="row" style={{ marginLeft: 0, marginRight: 0, marginTop: 0 }}>
            <div className="col-md-3 search-box-container">
                <div className="search-box container">
                    <div className="col-md-11 search-bubble">
                        <h3 className="search-text" style={{ paddingTop: 5 }}>subject</h3>

                        <FormControl fullWidth>
                            <InputLabel id="subject-select-input-label">subject</InputLabel>
                            <Select
                                labelId="subject-select-input-label"
                                id="subject-select-input"
                                defaultValue='null'
                                value={subject}
                                label="subject"
                                onChange={handleChange1}
                                
                            >
                                <MenuItem value={'null'}>all</MenuItem>
                                <MenuItem value={'math'}>math</MenuItem>
                                <MenuItem value={'literature'}>literature</MenuItem>
                                <MenuItem value={'history'}>history</MenuItem>
                                <MenuItem value={'geography'}>geography</MenuItem>
                                <MenuItem value={'physics'}>physics</MenuItem>
                                <MenuItem value={'biology'}>biology</MenuItem>
                                <MenuItem value={'chemistry'}>chemistry</MenuItem>
                            </Select>
                        </FormControl>

                        <h3 className="search-text">status</h3>

                        <FormControl fullWidth>
                            <InputLabel id="status-select-input-label">status</InputLabel>
                            <Select
                                labelId="status-select-input-label"
                                id="status-select-input"
                                defaultValue='null'
                                value={status}
                                label="status"
                                onChange={handleChange2}
                                
                            >
                                <MenuItem value={'null'}>all</MenuItem>
                                <MenuItem value={'school student'}>school student</MenuItem>
                                <MenuItem value={'university student'}>university student</MenuItem>
                            </Select>
                        </FormControl>

                        <h3 className="search-text">location</h3>

                        <FormControl fullWidth>
                            <InputLabel id="district-select-input-label">region</InputLabel>
                            <Select
                                labelId="district-select-input-label"
                                id="district-select-input"
                                defaultValue='null'
                                value={district}
                                label="location"
                                onChange={handleChange3}
                                
                            >
                                <MenuItem value={'null'}>all</MenuItem>
                                <MenuItem value={'option1'}>option1</MenuItem>
                                <MenuItem value={'option2'}>option2</MenuItem>
                                <MenuItem value={'option3'}>option3</MenuItem>
                                <MenuItem value={'option4'}>option4</MenuItem>
                                <MenuItem value={'option5'}>option5</MenuItem>
                            </Select>
                        </FormControl>

                    </div>
                </div>
            </div>

            <div className="col-md-9 tutor-list row">
                <TutorList subject={subject} status={status} district={district} />
            </div>
        </div>
    )
}

TutorList (where filtered tutors are supposed to appear):

const TutorList = (props) => {
    const [tutors, setTutors] = useState([])

    useEffect(() => {
        const fetchTutors = async () => {
            const data = await axios.get(`/api/v1/user/${props.subject}/${props.status}/${props.district}`)

            setTutors(data.data.users)
        }
        fetchTutors()
    }, [props])

    return (
        <Fragment>
            {tutors.map((tutor) => (
                ...
            ))}
        </Fragment>
    )
}

Backend:

exports.search = async (request, response, next) => {
    const subjectName = request.params.subject
    const statusName = request.params.status
    const districtName = request.params.district

    const users = await User.find({
        subject: subjectName, 
        district: districtName, 
        students: statusName
    })

    if (!users) {
        return next(
            new ErrorResponse(`User with these parameters doesn't exist`, 404)
        )
    }

    response.status(200).json({ success: true, users: users })
}

As you can see, I tried to use params for this, but soon realized one of the fields might be empty and it wont work. So what else am I supposed to do?
I just want an approximate example of how the request should look like in backend, I will dig to the rest myself. Would appreciate a push in the right direction, since I obviously cant see any other solutions for this.
Thanks in advance!

>Solution :

Frontend

const data = await axios.get(`/api/v1/user`, {
  params: {
    subject: props.subject,
    status: props.status,
    district: props.district
  }
})

Backend:

exports.search = async (request, response, next) => {
    const subjectName = request.query.subject
    const statusName = request.query.status
    const districtName = request.query.district
    // ...
})

Leave a ReplyCancel reply