我有一个MongoDB集合,可以使用$search
运算符使用输入字段中的值进行搜索,并且可以正常工作,当我控制台登录result
时,它仅向我显示匹配的那些文档搜索,但是我也希望它们在端点http://localhost:3001/search
上也可见,但是目前我列出了所有文档,如何列出搜索结果?我正在尝试res.send(result);
,但是它不起作用。这是我的尝试:
// Requiring the dependencies
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();
const mongoose = require('mongoose');
const PORT = process.env.PORT || 3001;
const BASE_URL = process.env.REACT_APP_BASE_URL;
const itemRoutes = express.Router();
let Comment = require('./comment.model');
app.use(cors());
app.use(bodyParser.json());
mongoose.connect(BASE_URL, { useNewUrlParser: true })
const connection = mongoose.connection;
connection.once('open', function () {
console.log('Connection to MongoDB established succesfully!');
});
let collection = connection.collection("posts_with_tags_test");
collection.createIndex(
{
postContent: 'text',
title: 'text'
}
);
itemRoutes.route('/search').post(async (req, res) => {
let result = await connection.collection("posts_with_tags_test").find({
$text: {
$search: req.body.queryString
}
}).toArray();
res.send(result);
console.log(result)
});
app.use('/search', itemRoutes);
app.listen(PORT, function () {
console.log('Server is running on' + ' ' + PORT);
})
这是我的输入字段:
import React, { Component } from "react";
import axios from "axios";
class Search extends Component {
getSearchQuery = () => {
const queryString = document.querySelector(
".search-input"
).value;
axios.post("http://localhost:3001/search", {
queryString: queryString,
});
console.log(queryString)
};
render() {
return (
<div>
<input
type="text"
className="search-input"
/>
<button type="submit" onClick={this.getSearchQuery}></button>
</div>
);
}
}
export default Search;
答案 0 :(得分:1)
如果您只是从浏览器访问localhost:3001 / search,它将不会显示,因为您没有发送要在查询中用作 req.body的数据{queryString:“ sample”} .queryString ,除非您使用的是邮递员
如果您要从前端访问它,请在React组件的getSearchQuery中尝试在 axios.post()上使用 .then()来接收来自您的后端
axios.post("http://localhost:3001/search", {
queryString: queryString,
}).then(response => {
console.log(response);
console.log(response.status);
console.log(response.data);
});