0

I'm developing website using MERN stack technologies. In that application I want to provide search facility. There is text box search button next to it. I want to open search results in new page. For example,

Data table contains products. If some user type 'milk' and click on search new page should show all milk product details.

when I click on search button it updated browser URL to this,

http://localhost:3000/search_result/this_is_search_string

This is the frontend code,

<form className="form-inline">
<input type="text"
  className="form-control"
  value={this.state.name}
  onChange={this.on_change_name}/>
<Link to={'/search_result/'+this.state.name} className="btn btn-primary">Search</Link> 
</form>

First problem is URL updated when click on button, but it not redirect to new page. In search_result page componentDidMount() method looks like this,

componentDidMount(){
        axios.get('http://localhost:4000/item/')
            .then(response => {
                this.setState({ search_result: response.data });
            })
            .catch(function (error) {
                console.log(error);
            })
    }

I want to pass url appended value to above function' 2nd line, axios.get('http://localhost:4000/item/') end of /item/. So I could load retrieved values to table.

Also in the backend controller file' method look like this.

export const get_items_by_name=(req,res)=>{
    //Item.find(req.params.id,(err,item)=>{{name: "Renato"}
    Item.find({name: "a"},(err,item)=>{
        if(err){
            res.send(err);
        }
        res.json(item);
    });
};

In SQL there is a way to perform select query with LIKE. But I'm new to MERN stack. So how could I update above method to search and retrieve values as URL appended.

I need your help guys how to figure out this. Thank for your help specially with implementation support.

  • Check this link: https://stackoverflow.com/questions/3305561/how-to-query-mongodb-with-like – Chris White Apr 26 '19 at 17:50
  • Possible duplicate of [How to query MongoDB with "like"?](https://stackoverflow.com/questions/3305561/how-to-query-mongodb-with-like) – Sam Curry Apr 26 '19 at 18:30

1 Answers1

1

In your problem you need to change your controller something like this try it,

export const get_items_by_name=(req,res)=>{
    //Item.find(req.params.id,(err,item)=>{{name: "Renato"}
    Item.find({name:`/.*${req.body.name}.*/` },(err,item)=>{
        if(err){
            res.send(err);
        }
        res.json(item);
    });
};

I tested this via postman and it works. You need to find way to do your page rendering part.

sashiksu
  • 354
  • 4
  • 15