Monday, 27 July 2020

How to build filter search using node/express?

Hi​I'm trying to build a filtered search in Node using express. Essentially a user selects criteria in a form, and I return results. I'm building this as a JSON API.​I receive a url which contains various query params (eg http://localhost:7777/property/search?county=kildare&bedrooms=2),​and this calls the following function​ exports.searchProperty = async (req, res) => { const query = { county: req.query.county || { $exists: true }, town: req.query.town || { $exists: true }, bedrooms: { $gte: parseInt(req.query.minbed) || 1, $lte: parseInt(req.query.maxbed) || 10, }, bathrooms: { $gte: parseInt(req.query.minbath) || 1, $lte: parseInt(req.query.maxbath) || 10, }, price: { $gte: parseInt(req.query.minprice) || 0, $lte: parseInt(req.query.maxprice) || 10000000, }, floorArea: { $gte: parseInt(req.query.minfloorarea) || 0, $lte: parseInt(req.query.maxfloorarea) || 10000, }, type: req.query.type || { $exists: true }, features: { $in: [req.query.features] } || { $exists: true }, }; const property = await Property.find(query); res.json({ items: property.length, property, }); }; ​Is there a better way to handle this. ie structure, handle fallbacks, and validation/security.

Submitted July 27, 2020 at 12:56PM by Deviso

No comments:

Post a Comment