0

I have db airport, there is TABLE tourists and in it COLUMN: id and also i have TABLE: flights, and there is column: listoftouristsbyid which is array of integers. I need to check if i passed to REST API request integer that is id of Tourist that not EXISTS. Means there is no tourist with given id (id is primary, autoincrementing key). I wrote something like that:

app.post('/flights', function(req, res) {
    pool.connect(function(err,client,done) {
        if(err) {
            return console.log("Error fetching clients", err);
        }
        client.query("SELECT tourists.id FROM tourists WHERE tourists.id = " + req.body.listoftouristsbyid[i], function (err, result) {
            done();
            if (result.rows === 0) {
                return console.log("Tourist "+req.body.listoftouristsbyid[i]+" you want to add does not exist" + err);
            }
        })
        client.query('INSERT INTO flights(departuredate, arrivaldate, numberofseats, listoftouristsbyid, ticketprice) VALUES($1, $2, $3, $4, $5)', 
            [req.body.departuredate, req.body.arrivaldate, req.body.numberofseats, req.body.listoftouristsbyid, req.body.ticketprice]);
        done();
        res.redirect('/flights');
    })
})

I know ITS A VALID QUERY, because when i type it in PSQL shell it returns

airport=#                                                                  
SELECT tourists.id FROM tourists WHERE tourists.id = 15;
 id 
----
(0 rows)

But its not working as javascript code - means code should terminate with error, but condition is not fulfiled. How do i write condition in Javascript that catches when SELECT tourists.id FROM tourists WHERE tourists.id = 15 gives 0 rows?

1
  • Has the connected user permissions to read the auto incremented key column? Commented Sep 27, 2018 at 12:04

1 Answer 1

1

In MySQL, When you perform a read operation, It will give you value in Array. So, get the length of the result array by result.length check if it is equal to zero.

When you perform a write or update operation, the result will contain a property affectedRows Which will tell you the number of rows affected. Print the result using console.sql('%j', result) and See if there is some option in PostGreSQL(Most probably there is).

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

Comments

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.