简体   繁体   中英

What is this syntax in Node.js and PostGres

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM