3

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?

2
  • 2
    Just a thought but, I don't think you'd want to do collection.find(req.query) unless you're validating req.query beforehand. You'd be exposing yourself to request injection and someone could walk through your db pretty easily just by doing collection.find({}) Commented Jun 8, 2016 at 18:19
  • @peteb Thanks for the advice! Commented Jun 8, 2016 at 18:57

2 Answers 2

4
//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
    })
}}
Sign up to request clarification or add additional context in comments.

Comments

0
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);

4 Comments

This doesn't answer the question of how to best construct a query string to pass in comparison operators
It definitely better addresses the question
@MedetTleukabiluly So is there not a more dynamic way? I'd have to write an if statement for each kind of comparison? And then on the client-side I'd have to flip a variable to every kind of comparison based on the user's interaction?
There is a way, called OData, but all query conditions must be handled on server, not sure if mongoose supports it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.