Skip to content

Returning id from query #49

Description

@finnhodgkin
const createUser = (username, firstname, lastname, address, password, cb) => {
  connection.query(
    `INSERT INTO users(username, firstname, lastname,address, password)
		VALUES($1,$2,$3,$4,$5)`,
    [username, firstname, lastname, address, password],
    (error, result) => {
      if (error) {
        cb(error);
      }
      connection.query(
        `select id from users where username=$1`,
        [username],
        (error, result) => {
          if (error) {
            cb(error);
          } else {
            cb(null, result.rows);
          }
        }
      );
    }
  );
};

In the above query you're inserting a user into the database and then getting that user's id and returning it. Postgres has inbuilt functionality for this with RETURNING id:

const createUser = (username, firstname, lastname, address, password, cb) => {
  connection.query(
    `INSERT INTO users(username, firstname, lastname,address, password)
		VALUES($1,$2,$3,$4,$5) RETURNING id`, ...
...

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions