bobbyz
bobbyz

Reputation: 5046

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?

Upvotes: 3

Views: 7484

Answers (2)

Sahiq saifi
Sahiq saifi

Reputation: 56

//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
    })
}}

Upvotes: 4

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11940

var filter = {};
if(req.query.type)
    filter.type = req.query.type;
if(req.query.price)
    filter.price = req.query.price;

// you cannot know if the incoming 
// price is for gt or lt, so

// add new query variable price_gt (price greater than)
if(req.query.price_gt) {
    filter.price = filter.price || {};
    filter.price.$gt = req.query.price_gt;
}

// add new query variable price_lt (price less than)
if(req.query.price_lt) {
    filter.price = filter.price || {};
    filter.price.$lt = req.query.price_lt;
}

collection.find(filter);

Upvotes: 0

Related Questions