As you can see below, I've set up a Postgres database and create a User Profile for each user. Then, I get the user ID and set the result of that query to 'res'. From there, I pull out the User ID value and run another query using the it. The only problem is this: I think sometimes these statements are executing out of order, because the user gets an empty string sent back to them.
app.post('/createUser', async function (request, response) {
const client = await pool.connect();
let phoneNumber = request.body.phoneNumber;
try {
await client.query('BEGIN')
await client.query(`INSERT INTO table (p_num) VALUES($1) ON CONFLICT DO NOTHING RETURNING *`, [phone]); //create a row in 'table' with user id and some values related to the user
let res = await client.query('SELECT * FROM table WHERE p_num = ($1)', [phone]) //fetches user id from the recently generated row in 'table'
var id = 0;
// res.rows should only return one row because the ID is a unique generated identifier, it's hacky but I wasn't sure how to do this better
for (row of res.rows) {
id = row.id;
}
await client.query('INSERT INTO table2 (uid) VALUES($1) ON CONFLICT DO NOTHING', [id]) //use the user id to run a query on another table
await client.query('COMMIT')
} catch (err) {
await client.query('ROLLBACK')
console.log(err)
} finally {
client.release()
response.send(String(id))
}
});
\d table returns:
Column | Type | Collation | Nullable | Default
--------------+---------+-----------+----------+----------------------------------------
id | integer | | not null | nextval('userstable_id_seq'::regclass)
phonenumber | text | | |
total_logins | integer | | not null | 0
Indexes:
"userstable_pkey" PRIMARY KEY, btree (id)
"unique_p_num" UNIQUE CONSTRAINT, btree (p_num)