Right approch to filter data from database
Solution 1:
Your code nows load all data from DB and filter in the frontend. This is not a good approach.
You have to filter in a mongo query and return only values you want. So you can try this code:
The frontend do this call (or whatever other structure you design for your URLs):
const res = await axios.get($'/api/users/{keyword}');
And the backend
router.get('/', async (req, res) => {
try {
const users = await User.find({
username: {
$regex: req.params.user,
$options: "i"
}
});
res.json(users);
} catch (error) {
console.log(error.message);
res.status(500).send('Server Error');
}
});
This query uses a regex with option i
which means is case insensitive. But maybe you don't want this option and simply send the keyword
in lowercase from the frontend.
Anyway the right approach is generate a "REST URL" and filter in the backend using a query in your DB. And in this way the frontend only will receive the data you want.
Example how the query works here