Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a query string with comparison operators in Express

If I have a resource in the database, I know I can use the mongodb npm package in my express app to filter something with $gt, $lt, etc. to only receive back the values based on my desired filter.

I also know how to use req.query in combination with mongodb to retrieve results of my query strings when they're equal to something (URL: http://localhost:3000/fruit?type=apple, Express/mongodb: collection.find(req.query)...).

How do I make it so the query string indicates I want only the values that are greater than or less than something? If I just wanted "equal to", I would just pass it in as another query parameter (http://localhost:3000/fruit?type=apple&price=1), but what if I want all fruits whose prices are less than 1?

like image 289
bobbyz Avatar asked Nov 27 '25 13:11

bobbyz


1 Answers

//if need to find ratings greater then 3
//The query string may be:
//127.0.0.1:8000/api/v1/posts?ratings[gt]=3
//if we check the req.query
//{ ratings: { gt: '3' } }

exports.getPosts = async (req, res) => {
try {
    const queryObj = { ...req.query };
    let queryStr = JSON.stringify(queryObj)
    queryStr = queryStr.replace(/\b(gt|gte|lt|lte|eq|ne)\b/g, match => `$${match}`);
    // queryStr  : {"ratings":{"$gt":"3"}}
    const posts = await Post.find(JSON.parse(queryStr));
    res.json({
        status: 'success',
        data: {
            posts
        }
    })
} catch (err) {
    res.status(401).json({
        status: 'error',
        message: 'Error in post finding',
        error: err
    })
}}
like image 148
Sahiq saifi Avatar answered Nov 30 '25 04:11

Sahiq saifi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!