如何使用react.js执行与mongo和mongoose的搜索查询?



我在这个项目中创建搜索组件时遇到了麻烦。基本上,这个想法是,搜索查询将接受一个name,搜索将过滤数据库,寻找与name一致或类似的产品。

最终,我尝试使用.find():

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

在后台使用POSTMAN测试时效果很好,因为它需要name,即const name = req.body.name

但是,在前端实现时,出现以下错误:前端:

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

错误:

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

因此,我开始想知道ATLAS搜索是否可行,或者是否有修复此错误的方法

我将如何使用ATLAS搜索和react.js在一起?

编辑因此,在实现req.query后,后端API端点仍然像预期的那样工作,前端似乎发送了正确的查询,但是现在json结果没有被发送回来下面是代码

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)
}
}

上面的代码是在反应,并发送取与正确的查询和搜索输入,然而FilteredProduct没有返回任何东西,即使它已被设置为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

您正在发送GET请求的请求正文,请尝试发送查询参数,如下所示:

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

注意,这里没有使用Atlas Search,只是使用正则表达式调用一个简单的MQLfind。为了使用Atlas Search(假设您已经创建了一个搜索索引),您必须使用aggregate方法传递一个具有$search阶段的聚合管道。