0

Hi came across this syntax in a node.js application, in which we are making a SELECT query to our postgres database.

app.get("/monsters/:id", (req, res, next) => {
    let id = req.params.id;
    pool.query(`SELECT * FROM monsters WHERE id = $1`, [id], (err, response) => {
        if (err) return next(err);
        console.log(response.rows);
        res.send(response.rows);
    })
});

I don't understand the follow the line: pool.query(SELECT * FROM monsters WHERE id = $1, [id], (err, response) => {

how does this kind of string literal work, where we have used $1 and passing an array?

Thank you

6
  • That's a template literal Commented Apr 21, 2020 at 7:59
  • Also $1 is not connected to the string literal - it's just a normal part of the text inside. It's used by the SQL engine to be replaced with an appropriate parameter. Commented Apr 21, 2020 at 8:00
  • it is adding the first element of the [id] array. So what does $1 represent? Commented Apr 21, 2020 at 8:02
  • It's the parameter in the array. It's just a parametarised query. Commented Apr 21, 2020 at 8:04
  • Thank you, so again this has to do with SQL syntax and not JS ? Commented Apr 21, 2020 at 8:06

1 Answer 1

3

This has nothing to do with javascript or node.js syntax. The string

`SELECT * FROM monsters WHERE id = $1`

is the same as:

"SELECT * FROM monsters WHERE id = $1"

because there is no interpolation done within the string.

From the point of javascript, $1 literally represents $1 and nothing else.

I don't quite know the library you are using for accessing postgres but it looks fairly obvious to me that $1 is mapped to the first element of [id] (which is just the value of id). It looks like the postgres library used maps $1 to ? in SQL syntax and moves the values in the second argument to the appropriate part of the generated sql query.

I would look at the documentation for the library used to access postgres for more info on the API.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I was so confused by that syntax. But this clears it up!

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.