0

I use node.js and pg library (node-postgres) to interact with database.

This is the code I use to retrieve one user of specific ID:

const { rows: users } = await db.query("SELECT * FROM users WHERE id = $1", [id]);
const user = users[0];

Even if there is only one record postgres always returns an array, so I retrieve this first item in the second line.

Is there a way to shorten this code if there is only one user? Like make it one line instead of two.

1 Answer 1

2

You can directly get the first user object by destructuring the rows array

const { rows: [user] } = await db.query(...)
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.