My question is, is this a good approch to filter and get specific data from the database, or will it stress my database in the futur with all the queries that will be made. I'm using this to suggest to the user a fetched list based on his keyword rather than a one direct API response. Using react by the way.
const [data,setData] = useState([]);
const [keyword,setKeyword] = useState('');
useEffect(() => {
const fetchData = async keyword => {
let filteredUsers;
try {
const res = await axios.get('/api/users');
filteredUsers= res.data.filter(user=>
user.username.toLowerCase().includes(keyword)
);
setData(filteredUsers);
} catch (error) {
console.error(error);
}
setLoadingdata(false);
};
keyword.length > 1 && fetchData(keyword);
}, [keyword]);
Backend :
router.get('/', async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (error) {
console.log(error.message);
res.status(500).send('Server Error');
}
});
CodePudding user response:
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
