-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
A way to get the id of inserted row as callback? #1269
Comments
|
Got to this the long way. Can you update the docs (specifically at https://node-postgres.com/features/queries#parameterized-query) ---to use this syntax? I've used RETURNING before when doing a data-modifying WITH clause, but I didn't think to add it to a plain insert. (also, my way of using it is with async/await...) Suggestion: const text = 'INSERT INTO users(name, email) VALUES($1, $2) RETURNING *'
const values = ['brianc', '[email protected]']
// callback
client.query(text, values, (err, res) => {
if (err) {
console.log(err.stack)
} else {
console.log(res.rows[0])
}
})
// promise
client.query(text, values)
.then(res => console.log(res.rows[0]))
.catch(e => console.error(e.stack))
// async/await, pool
try {
const pool = new Pool()
const {rows} = await pool.query(text, values)
console.log(rows[0])
}catch(e){
console.error(e)
setImmediate(() => { throw e })
} |
You don’t always need |
@jmarca I agree you don't always need a https://node-postgres.com/features/queries#parameterized-query |
Yes of course you don't always need "returning", and postgresql inserts typically just return the sparse phrase That's the trouble with switching between different languages and databases...one remembers the broad stokes but forgets the details. Thanks for the addition to the docs |
I'm using KnexJS and have the same problem, solve using "returning" just like this: // Returns [1] |
For inserting a row, the callback just sends back this:
Is there a way to get the id of the inserted row?
The text was updated successfully, but these errors were encountered: