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)
getUserBySearch
logic:
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
I should only be receiving the users whose name
field include test
; however I get back 200 response with ALL of the users in the DB. how can I only retrieve the users related to my search query?
2
Answers
In your case
http://localhost:3001/user/search?searchQuery=test
,you should be accessing the
?searchQuery=test
asreq.query.searchQuery
:Since, you were wrongly reading the query value, you had
undefined
as a value foruser
constant, hence getting all users in the DB.and in the search form try this,#
try like this ,