Search code examples
node.jspostgresqlexpresspg-promise

Retrieve inserted row using pg-promise npm module in Express.js


I am inserting a user row into Postgres from Express.js like as follows:

db.none("INSERT INTO users (email, password) VALUES (${incoming.email}, crypt(${incoming.password}, gen_salt('bf')))",{
    incoming: { email: qemail, password: qpwd}
  }
).then(function (data) {
  // data is null
});

The email and password come from the query parameters on the React.js frontend. I use this query for the signup action on my application and wanted to know if I could get this newly added user back from this same query. I just felt that making another get request right after the signup to get the user info was inefficient, which I do for my login action. Thanks in advance.


Solution

  • Append RETURNING * to your query, and replace none with method one.

    const row = await db.one("INSERT INTO users(email, password) VALUES(${incoming.email}, 
                              crypt(${incoming.password}, gen_salt('bf'))) RETURNING *",
        {
            incoming: { email: qemail, password: qpwd}
        }
    );
    
    // row = the newly inserted row