The approach you are taking is wrong. It will not work. Stop.
Go read the guidance on upserts:
and then use one of the correct methods documented there, either locking the table and doing the upsert, or doing it in a retry loop.
To understand why your current approach is wrong, think about what happens when two people do the same command at the same time.
- person1:
select * from waiter
- person2:
select * from waiter
- person1:
if exist(...)
=> false, nope, doesn't exist
- person2:
if exist(...)
=> false, nope, doesn't exist
- person1:
insert...
- person2:
insert...
and boom, you have two records.
(This approach is also awfully inefficient - the SELECT * FROM WAITER
is just horrible).
That's why everyone's giving you links to articles and documentation showing you how to do it right. You're trying to solve the wrong problem. You're effectively saying "When I drive my car into the intersection without looking at the traffic lights, how do I know if somebody else is already there?". We're saying "Uh, don't do that. Look at the traffic lights."
Only once you have the actual upsert ("create if not exists") operation correct, then worry about how to deal with it from node.js.
I'd say it'll be like any other query, anyway: Run query/command, get id (either existing or newly created) as result from query, use ID however you want. If you need more help with that part, try posting a node.js specific question on just that part, without all the incorrect-upsert-code mess to throw everybody off track. Consider that many on the postgresql tag won't know much about node.js anyway.