I have the following code for a GET route on an API call to a Mongoose database, I want to use a query string to find all items containing various words, an example path would be:
/cpu=i3&username=bob
This should result in all people with a CPU that has i3 in it with a name containing bob (an odd example!).
The CPU could be of any generation and actually contains things like:
Intel(R) Core(TM) i3-8109U CPU @ 3.00GHz or Intel(R) Core(TM) i3-3220 CPU @ 3.30GHz
And the name could be bob smith, bob jones, bob you get the idea!
I can do it using regex like this:
const foundAsset = await Asset.find({'cpu': {'$regex': '.*i3.*'}});
the issue for me is that obviously I can't hard code cpu or i3 in there as it could be anything, fo example it could just be searching for username=bob rather than cpu=i3, I'm reading the query string like this:
.get(async (req, res) => {
let options = {
...req.query
};
and returning it like this:
const foundAsset = await Asset.find(options);
res.json({
status: 'success',
data: foundAsset
});
} catch (e) {
console.log(e);
}
Obviously putting Options in place of i3 in the regex would make sense but clearly won't work as options has this { cpu: 'i3' }, I could of course put something like options.cpu which would return just the CPU but what do I then do if somebody wants to search for a username LIKE bob.
I do know what each of the query strings are likely to be and so could loop through each query string?
thanks
Your thinking is not wrong with the opitons object you just need to transform the query data to use the mongo regex operator.
So your code would be something like this:
cosnt options= Object.keys(req.query).reduce(
(accumulator, key) => {
accumulator[key] = {'$regex': `.*${req.query[key]}.*`}
return accumulator;
},{})
const foundAsset = await Asset.find(options);