porsager / postgres

Postgres.js - The Fastest full featured PostgreSQL client for Node.js, Deno, Bun and CloudFlare
The Unlicense
7.03k stars 255 forks source link

Getting Inserted id #887

Closed kryptus36 closed 1 month ago

kryptus36 commented 1 month ago

I'm just checking to see if there's a better way to attach a postgres-generated ID to an existing object?

gameType.id = (await this.db INSERT INTO game_types ${this.db(gameType)} RETURNING id)[0].id;

This works, but doesn't feel like it's the best way to do it.

mattbishop commented 1 month ago

I like to use destructuring:

const [{id: gtId}] = (await this.db`INSERT INTO game_types ${this.db(gameType)} RETURNING id`);
gameType.id = gtId;

This takes the first element of the result set, pulls the id value into gtId that you can then assign to your gameType var.

kryptus36 commented 1 month ago

Thanks, that's what I wanted but couldn't find the right syntax. Ultimately I settled on returning * and getting the whole object back. Same idea though, destructuring it works well.