Query Postgres Table to find Record with Email

Viewed 16

I have the following code in my Express.js API. It simply selects all records in a table called users where the email is equal to the email argument. However, their is an issue with using '@' symbol; it only searches for everything preceeding the '@' (i.e. searching for 'someone@place.com' would actually search 'someone').

I understand that Postgres have a series of special characters that need to be escaped using a backslash but when I do that, it get the following error error: syntax error at or near "\".

Are their anyways to select all records in a table where a certain value is equal to a string that contains special characters?

const getUserByEmail = async (email) => {
  try {
    const results = await pool.query(`
            SELECT *
            FROM users
            WHERE email = ${email};
        `);
    return results.rows;
  } catch (err) {
    return err.stack;
  }
}
1 Answers

Don't worry, I found a solution. The solution was to use placeholders instead of using template literals. Below is my solution:

const getUserByEmail = async (email) => {
  try {
    const results = await pool.query("SELECT * FROM users WHERE email = $1", [email]);
    return results.rows;
  } catch (err) {
    return err.stack;
  }
}
Related