title: How to find records from database according to the typed string in the ReactJS search bar
body: <p>I want to fetch records (Which are of vehicles ad) from mongoDB database that matches with the keyword that I type in the search bar and display them in reactJS frontend. The database Schema of record(Vehicle ad) consist of fields like  <strong>(make, address, registeration,year,intcolor,extcolor,transmission,bodytype,category,model)</strong>. So if a user type something like this <strong>Toyota in Lahore</strong> in search bar the user should get all the records(Vehicle ads) where <strong>make is toyota</strong> and <strong>address is lahore</strong>.</p>
  <p><strong>Here is my frontend code</strong></p>
  <p><strong>Homefilter.js</strong> (Which gets data from search bar and save it in a variable and send it to another <strong>searchAd.js</strong> file)</p>
  <pre><code>import React, { useEffect, useState } from 'react';
  import './HeroSection.css';
  import axios from 'axios';
  import { useHistory } from 'react-router-dom';
  import SearchAd from './SearchAd';
  
  function Homefilter() {
    const [search, setSearch] = useState('');
    const history = useHistory();
  
    const Getsearch = () =&gt; {
      console.log(search);
      history.push(`/searchpage/${search}`);
    };
  
    return (
      &lt;div class='container-fluid'&gt;
        &lt;div
          style={{ height: '350px', alignItems: 'center' }}
          class='row'
          id='colu'
        &gt;
          &lt;div class='col-lg-12 col-md-12 col-sm-12'&gt;
            &lt;div
              style={{
                justifyContent: 'center',
                alignContent: 'center',
                alignItems: 'center',
                textAlign: 'center',
              }}
            &gt;
              &lt;input
                style={{ display: 'inline', width: '35rem' }}
                type='text'
                name='search'
                class='form-control'
                placeholder='Enter keyword to search Vehicle'
                value={search}
                onChange={(e) =&gt; setSearch(e.target.value)}
              /&gt;
              &lt;button onClick={Getsearch} class='btn btn-primary'&gt;
                Search
              &lt;/button&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    );
  }
  
  export default Homefilter;
  </code></pre>
  <p><strong>SearchAd.js</strong> (Which receive variable from <strong>Homefilter.js</strong> and send it in GET request to backend**</p>
  <pre><code>import React, { useEffect, useState } from 'react';
  
  import axios from 'axios';
  import './Allads.css';
  import { useParams } from 'react-router-dom';
  
  const SearchAd = () =&gt; {
    const { search } = useParams();
    console.log(search);
    const [data, setData] = useState('');
    const stringse = JSON.stringify(search);
    console.log(stringse);
  
    const Getsearch = () =&gt; {
      axios
        .get('/searchdata', { params: { stringse } })
        .then((response) =&gt; {
          setData(response.data.data);
          console.log(response);
        })
        .catch((error) =&gt; {
          console.log(error);
        });
    };
  
    useEffect(() =&gt; {
      Getsearch();
    }, []);
  
    if (data.length &gt; 0) {
      return data.map((datas, index) =&gt; {
        console.log(datas);
        return (
          &lt;div className='datas' key={datas._id}&gt;
            &lt;div style={{ marginTop: '20px' }} class='container-fluid'&gt;
              &lt;div class='row'&gt;
                &lt;div class='col-lg-1 col-md-1 col-sm-1 '&gt;&lt;/div&gt;
  
                &lt;div class='col-lg-4 col-md-4 col-sm-4 '&gt;
                  &lt;div
                    style={{ backgroundColor: '#1c2237', height: '180px' }}
                    class='row'
                  &gt;
                    &lt;div class='col-lg-12 col-md-12 col-sm-12'&gt;
                      &lt;h3 style={{ color: '#f00946' }}&gt;
                        {datas.make} {datas.model}
                      &lt;/h3&gt;
                      &lt;p&gt;
                        &lt;b&gt;{datas.location.formattedAddress}&lt;/b&gt;
                      &lt;/p&gt;
                      &lt;p&gt;
                        {datas.year} | {datas.mileage} Km | interior:{' '}
                        {datas.intcolor} | exterior: {datas.extcolor} |{' '}
                        {datas.engine} cc | {datas.transmission} |
                        {datas.registeration} Registered | {datas.bodytype} |{' '}
                        {datas.category}
                      &lt;/p&gt;
                      &lt;p&gt;Updated: {datas.createdAt} &lt;/p&gt;
                    &lt;/div&gt;
                  &lt;/div&gt;
  
                  &lt;div
                    style={{ backgroundColor: '#f00946', height: '180px' }}
                    class='row'
                  &gt;
                    &lt;div class='col-lg-12 col-md-12 col-sm-12'&gt;
                      &lt;h5 style={{ color: '#1c2237' }}&gt; PKR: {datas.price} &lt;/h5&gt;
                      &lt;p style={{ marginTop: '70px' }}&gt;
                        &lt;b&gt;mob #:&lt;/b&gt;
                        {datas.mobilenumber}
                      &lt;/p&gt;
                    &lt;/div&gt;
                  &lt;/div&gt;
                &lt;/div&gt;
  
                &lt;div class='col-lg-6 col-md-6 col-sm-6 '&gt;
                  &lt;div style={{ backgroundColor: 'white' }} class='row'&gt;
                    &lt;div class='col-lg-4 col-md-4 col-sm-4  '&gt;
                      &lt;img
                        className='zoomimg'
                        src={`http://localhost:3000/uploads/profilepics/${datas.images[0]}`}
                        alt='abc'
                      /&gt;
                    &lt;/div&gt;
                    &lt;div
                      style={{ paddingRight: '100px' }}
                      class='col-lg-4 col-md-4 col-sm-4 '
                    &gt;
                      &lt;img
                        className='zoomimg'
                        src={`http://localhost:3000/uploads/profilepics/${datas.images[1]}`}
                        alt='abc'
                      /&gt;
                    &lt;/div&gt;
                    &lt;div class='col-lg-4 col-md-4 col-sm-4 '&gt;
                      &lt;img
                        className='zoomimg'
                        src={`http://localhost:3000/uploads/profilepics/${datas.images[2]}`}
                        alt='abc'
                      /&gt;
                    &lt;/div&gt;
                  &lt;/div&gt;
  
                  &lt;div style={{ backgroundColor: 'white' }} class='row'&gt;
                    &lt;div class='col-lg-4 col-md-4 col-sm-4 '&gt;
                      {' '}
                      &lt;img
                        className='zoomimg'
                        src={`http://localhost:3000/uploads/profilepics/${datas.images[3]}`}
                        alt='abc'
                      /&gt;
                    &lt;/div&gt;
                    &lt;div class='col-lg-4 col-md-4 col-sm-4 '&gt;
                      {' '}
                      &lt;img
                        className='zoomimg'
                        src={`http://localhost:3000/uploads/profilepics/${datas.images[4]}`}
                        alt='abc'
                      /&gt;
                    &lt;/div&gt;
                    &lt;div class='col-lg-4 col-md-4 col-sm-4 '&gt;
                      {' '}
                      &lt;img
                        className='zoomimg'
                        src={`http://localhost:3000/uploads/profilepics/${datas.images[5]}`}
                        alt='abc'
                      /&gt;
                    &lt;/div&gt;
                  &lt;/div&gt;
                &lt;/div&gt;
  
                &lt;div class='col-lg-1 col-md-1 col-sm-1 '&gt;&lt;/div&gt;
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        );
      });
    } else {
      return &lt;h3&gt;no more ads&lt;/h3&gt;;
    }
  };
  
  export default SearchAd;
  </code></pre>
  <p><strong>Backend code</strong></p>
  <pre><code>router.get('/searchdata', async (req, res, next) =&gt; {
    console.log(req.query.stringse);
    const searchad = req.query.stringse;
  
    try {
      const mads = await Ads.find({ $text: { $search: searchad } });
      console.log(mads);
      return res.status(200).json({
        success: true,
        count: mads.length,
        data: mads,
      });
    } catch (err) {
      console.log(err);
      res.status(500).json({ error: 'server error' });
    }
  });
  </code></pre>
  <p><strong>Vehicle Ads Schema</strong></p>
  <pre><code>const mongoose = require('mongoose');
  const geocoder = require('../utils/geocoder');
  
  const adsSchema = new mongoose.Schema({
    registeration: {
      type: String,
      required: true,
      index: true,
    },
  
    intcolor: {
      type: String,
      required: true,
      index: true,
    },
    extcolor: {
      type: String,
      required: true,
      index: true,
    },
    mileage: {
      type: Number,
      required: true,
    },
    price: {
      type: Number,
      required: true,
    },
    make: {
      type: String,
      required: true,
      index: true,
    },
    model: {
      type: String,
      required: true,
      index: true,
    },
    year: {
      type: Number,
      required: true,
      index: true,
    },
    discription: {
      type: String,
      required: true,
    },
    mobilenumber: {
      type: Number,
      required: true,
    },
  
    address: {
      type: String,
      required: true,
      index: true,
    },
    images: {
      type: Array,
      required: true,
    },
    transmission: {
      type: String,
      required: true,
      index: true,
    },
    engine: {
      type: String,
      required: true,
    },
    userId: {
      type: String,
      required: true,
    },
    serial: {
      type: String,
      required: true,
    },
    bodytype: {
      type: String,
      required: true,
      index: true,
    },
    category: {
      type: String,
      required: true,
      index: true,
    },
  
    location: {
      type: {
        type: String,
        enum: ['MultiPoint'],
      },
      coordinates: {
        type: [Number],
        index: '2dsphere',
      },
      formattedAddress: {
        type: String,
      },
    },
    createdAt: {
      type: Date,
      default: Date.now,
    },
  });
  
  adsSchema.index({
    make: 'text',
    address: 'text',
    registeration: 'text',
    year: 'text',
    intcolor: 'text',
    extcolor: 'text',
    transmission: 'text',
    bodytype: 'text',
    category: 'text',
    model: 'text',
  });
  adsSchema.pre('save', async function (next) {
    const loc = await geocoder.geocode(this.address);
    this.location = {
      type: 'multipoint',
      coordinates: [loc[0].longitude, loc[0].latitude],
      formattedAddress: loc[0].formattedAddress,
    };
    next();
  });
  
  const Ads = mongoose.model('ADS', adsSchema);
  module.exports = Ads;
  </code></pre>
  <p>Currently my code is working in such a way that if I type individual keyword like if a type (toyota) it will show me all vehicles ad with <strong>make=toyota</strong> and if i type (Lahore) it will show me all the vehicles ad with <strong>address=Lahore</strong>. But when I type (toyota in Lahore) it does not show anything</p>