[英]MongoDB find user by search returning all users
I am trying to query a user by their name field, and I am testing it in insomnia.我正在尝试通过他们的姓名字段查询用户,并且我正在对其进行失眠测试。 I have my user schema like so:我有这样的用户架构:
const userSchema = mongoose.Schema({
id: { type: String },
name: {
type: String,
required: true,
},
companion: {
type: String,
required: false
},
bio: {
type: String,
required: false
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
min: 5
},
userImage: {
type: String,
required: false,
},
});
And I have my route for /search which runs the getUserBySearch function: router.get('/search', getUserBySearch)
我有我的 /search 路线,它运行 getUserBySearch function: router.get('/search', getUserBySearch)
getUserBySearch
logic: getUserBySearch
逻辑:
export const getUserBySearch = async (req, res) => {
// tried req.query and req.query.search
const { searchQuery } = req.params
try {
// make the search query not case sensitive
const user = new RegExp(searchQuery, `i`)
//find the user's name using the name field
const userFound = await User.find({name: user})
res.json({data: userFound})
} catch (error) {
res.status(404).json({message: error.message})
}
}
Tested in insomnia under the route: http://localhost:3001/user/search?searchQuery=test
在路由下失眠测试: http://localhost:3001/user/search?searchQuery=test
I should only be receiving the users whose name
field include test
;我应该只接收name
字段包含test
的用户; however I get back 200 response with ALL of the users in the DB.但是我得到了数据库中所有用户的 200 响应。 how can I only retrieve the users related to my search query?我怎样才能只检索与我的搜索查询相关的用户?
In your case http://localhost:3001/user/search?searchQuery=test
, you should be accessing the ?searchQuery=test
as req.query.searchQuery
:在您的情况下http://localhost:3001/user/search?searchQuery=test
,您应该访问?searchQuery=test
作为req.query.searchQuery
:
const { searchQuery } = req.query;
const user = new RegExp(searchQuery, `i`);
Since, you were wrongly reading the query value, you had undefined
as a value for user
constant, hence getting all users in the DB.由于您错误地读取了查询值,因此您undefined
为user
常量的值,因此将所有用户都放入数据库中。
exports.searchRecipe = async(req,res) => {
try {
let searchTerm = req.body.searchTerm;
let user = await user.find( { $text: { $search: searchTerm, $diacriticSensitive: true } });
res.render('search', {user} );
} catch (error) {
res.satus(500).send({message: error.message || "Error Occured" });
}
}
and in the search form try this,#在搜索表单中试试这个,#
<form method="POST" action="/search">
<input type="search" name="searchTerm" class="form-control" placeholder="Search..." aria-label="Search">
</form>
try like this,试试这样
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.