Search code examples
reactjsmongodbmongoosesearchmongodb-atlas-search

How to perform search query with mongo and mongoose with react.js?


I've been having trouble with creating a search component in this project. Basically, the idea is that the search query will take in a name and the search will filter the database finding products that coincide with or are like name.

Ultimately, I've tried using a .find():

const product =  await Product.find({ name: new RegExp(name, 'i') })

which works well on the backend when tested with POSTMAN as it takes in name which is const name = req.body.name

However, when implemented on the front-end, the following error occurs: Frontend:

    const handleSearch = async (e) => {
        const product = {search}

        const response = await fetch('/api/products/search', {
            body: JSON.stringify(product),
            headers: {
                'Content-Type': 'application/json'
            } 
        })

Error:

TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body

So, I began wondering if ATLAS search is the way to go, or is there a fix to this error

How would i go about using ATLAS search and react.js together?

Edit So after implementing the req.query the backend API endpoint still works as expected and the frontend does seem to send the correct query, however now the json result is not being sent back Below is code

const handleSearch = async (e) => {
        e.preventDefault()
        console.log(search)
        const product = {search}
        const response = await fetch(`/api/products/search?${new URLSearchParams(product).toString()}`)

        const json = await response.json()
        
        if (!response.ok) {
            setError(json.error)
        }

        if (response.ok) {
            setError('')
            setSearch('')
            setFilterProduct(json)
        }

    }

the above code is in react and does send the fetch with the correct query and search input, however FilteredProduct returns nothing even through it has been set as the json.

const searchProduct = async (req, res) => {
    const search = req.query.search
    console.log(req.query.search)
    const product =  await Product.find({ name: new RegExp(search, 'i') })

    if (!Product) {
        return res.status(400).json({error: 'enter proper search'})
    }

    res.status(200).json(product)
    
}
 

Thanks for help


Solution

  • You are sending request body for GET request, try sending query params, like this:

    const handleSearch = async (e) => {
          const product = {search};
          const response = await fetch(`/api/products/search?${new URLSearchParams(product).toString()}`)
     }