Joe P
Joe P

Reputation: 73

How to query MongoDB database using MongoDB, Express, React, and Node?

I cannot for the life of me figure out how to use a React, Express, Node, and MongoDB together to query the MongoDB database and display that information onto the DOM. My query works when hardcoded in, but when using the front-end text input, it does not work. Here is the code:

React Component:

const { facilities } = this.props.facility;
        return(
            <Container>

                <Form onSubmit={this.onSubmit}>
                    <FormGroup>
                        <Input
                        type="text"
                        name="facilityState"
                        id="facilityState"
                        placeholder="Search State"
                        value={query}
                        onChange={this.onChange}
                        />
                    </FormGroup>
                    <Button
                        color="dark"
                        style={{marginTop: '2rem'}}
                        block                    
                    > Search </Button>
                </Form>

                <Button onClick={this.checkReduxState}> Check Redux State </Button>

                { this.props.isAuthenticated ? 

                <ListGroup>
                    <TransitionGroup className="facilities-list">
                        {facilities.map(({_id, name, address, city, state, zip, phone, email}) => (
                            <CSSTransition key={_id} timeout={500} classNames="fade">
                                <ListGroupItem> 
                                { this.props.isAuthenticated ? 
                                <Button
                                className="remove-btn"
                                color="danger"
                                size="sm"
                                onClick={this.onDeleteClick.bind(this, _id)}
                                > &times;</Button> : null }


                                   <p> {name} </p> 
                                   <p> {address} </p>
                                   <p> {city} </p>
                                   <p> {state} </p>
                                   <p> {zip} </p>
                                   <p> {phone} </p>
                                   <p> {email} </p>

                                </ListGroupItem>
                            </CSSTransition>
                        ))}
                    </TransitionGroup>
                </ListGroup> : null

                }

            </Container>

Express Route:

router.get('/query', (req, res) => {
    Facility.find({
        state: req.body.facilityState
        // state: req.query.facilityState 
    })
        .then(facilities => res.json(facilities));
});

Mongoose Schema:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// mongoose.set('useCreateIndex', true);

const FacilitySchema = new Schema({
    name: {
        type: String,
        required: true
    },
    address: {
        type: String,
        // text: true,
        required: true
    },
    city: {
        type: String,
        required: true
    },
    state: {
        type: String,
        text: true,
        index: true,
        required: true
    },
    zip: {
        type: Number,
        required: true
    },
    phone: {
        type: Number,
        required: true
    },
    email: {
        type: String,
        required: true
    },
});

// FacilitySchema.index({state: 'text'});


module.exports = Facility = mongoose.model('facility', FacilitySchema);

When I hard code the desired string value in for req.body.facilityState, pressing the submit button on the user interface works. Also, when using Postman this route works. But for some reason, the express req.body(or req.query) and the component aren't communicating with each other like they should. Can anyone help with this?

EDIT Here is onChange function:

onChange = (e) => {
        this.setState({ [e.target.name] : e.target.value })
    }

EDIT 2

Here is redux action file query:

export const queryFacilities = () => dispatch => {
    dispatch(setFacilitiesLoading());
    axios
        .get('/api/facilities/query')
        .then(res => 
            dispatch({
                type: QUERY_FACILITIES,
                payload: res.data
            }))
        .catch(err => dispatch(returnErrors(err.response.data, err.response.status)));
}

Upvotes: 1

Views: 5026

Answers (1)

Joe P
Joe P

Reputation: 73

I fixed the issue by changing my API call from

router.get('/query', (req, res) => {
    Facility.find({
        state: req.body.facilityState
        // state: req.query.facilityState 
    })
        .then(facilities => res.json(facilities));
});

to

router.get('/query/:state', (req, res) => {
    Facility.find({
        state: req.params.state
    })
        .then(facilities => res.json(facilities));
});

and also changing my Redux action from

export const queryFacilities = () => dispatch => {
    dispatch(setFacilitiesLoading());
    axios
        .get('/api/facilities/query')
        .then(res => 
            dispatch({
                type: QUERY_FACILITIES,
                payload: res.data
            }))
        .catch(err => dispatch(returnErrors(err.response.data, err.response.status)));
}

to

export const queryFacilities = (state) => (dispatch, getState) => {
    dispatch(setFacilitiesLoading());
    axios
        .get(`/api/facilities/query/${state}`)
        .then(res => 
            dispatch({
                type: QUERY_FACILITIES,
                payload: res.data
            }))
        .catch(err => dispatch(returnErrors(err.response.data, err.response.status)));
}

So essentially I was able to pass my input through to the API by using req.params, not by using req.body.

Upvotes: 3

Related Questions