1

I'm trying to write a constraint code that will display a message when someone tries to search for an id that doesn't exist in the database (PostgreSQL) but the if statement code below doesn't seem to do anything I keep getting status 200 ok on postman even though the id doesn't seem to exist. How can I fix this?

Code below:

Database query:

const findFruit = async (req, res) => {

    const {id } = req.params;
    try {
        const findfru = await pool.query("SELECT * FROM fruits WHERE fruit_id=$1", [id]);

        if (!findfru ) {
            return res.status(400).send(e)
        }

        res.json(findfru .rows[0])

    } catch (e) {
        res.status(500).send(e)

    }
}

Route API:

router.get("Fruits/:id", findFruit )
2
  • 1
    What is e in res.status(400).send(e)? Commented Jun 27, 2021 at 19:01
  • This has nothing to do with database constraints. Commented Jun 27, 2021 at 19:02

1 Answer 1

3

If the ID isn't in the database the query still succeeds, it just returns no rows. You should check the number of rows explcitily:

if (findfru.rows.length === 0) {
    return res.status(400).send(`${id} not found`);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I see, it works perfectly fine now thanks!

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.