0

My current query looks like this:

router.get('/search?', function(req, res, next) {
    var title = req.query.title;
    var active = req.query.active;
    var sql = "SELECT * from users WHERE title = ? AND active = ?"; 
    connection.query(sql, [title, active], function (error, results, fields) {
        res.json({"status": 200, "error": null, "response": results});
    });
});

It works it I enter:

localhost:4001/api/v1/users/search?title=mr&active=1

But it doesn't work if one is not set:

localhost:4001/api/v1/users/search?title=mr

{"status":200,"error":null,"response":[]}

How can I make the query and return the desired string regardless if one or the other search parameter is set or not? So like:

localhost:4001/api/v1/users/search?title=mr
localhost:4001/api/v1/users/search?active=1 
localhost:4001/api/v1/users/search?title=mr&active=1
localhost:4001/api/v1/users/search?active=1&title=mr    

1 Answer 1

2

you can try to build your query dynamically according to the params set in the request:

router.get('/search?', function(req, res, next) {
    var sql = "SELECT * from users ";
    const existingParams = ["title", "active"].filter(field => req.query[field]);

    if (existingParams.length) {
        sql += " WHERE ";
        sql += existingParams.map(field => `${field} = ?`).join(" AND ");
    }

    connection.query(
        sql,
        existingParams.map(field => req.query[field]),
        function (error, results, fields) {
            res.json({"status": 200, "error": null, "response": results});
        }
    );
});

this way if you want to handle more params you can just add them the "existingParams" statement

Sign up to request clarification or add additional context in comments.

4 Comments

You have missed last condition var sql = "SELECT * from users"; const existingParams = ["title", "active"].filter(field => req.query[field]); if (existingParams.length !== 0) sql += ' WHERE ';
Unfortunately its not working properly ... I provided the results above.
Rahul is right. if (existingParams.length !== 0) sql += ' WHERE '; was missing ... but also existingParams should be in the .query() ... instead I need to defined them depending if available. The above is working. Not sure if that is the best way to do so though
yeah sorry for the different mistakes, i edited the answer

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.