使用参数化查询在nodejs中返回Postgres结果



如何在Nodejs中使用参数化查询返回结果?

如果我删除RETURNING*,查询运行良好

现在,服务器返回这个错误

错误:"处或附近的语法错误;返回";

server.js

const text = "UPDATE users SET info = JSONB_SET(info, '{geometry,coordinates}', '"+coords+"') WHERE id=$1 RETURNING*";
const values = [id];
pool.query(text, values, (err, res) => {
if (err) {
//log errors
console.log(err.stack);
//return error to client
} else {
//success
//console.log(res.rows);

}
});

要在node中使用postgres参数化查询,正确的方法是使用promise语法。Github上也出现了类似的问题。

我在问题中使用的语法问题似乎是,pg将$1作为文本字符串的一部分而不是占位符读取,因为它被引号包裹。

Promise语法似乎解决了这个问题。嗯,对我有用。

更新查询

const queryOpts = {
text: "UPDATE users SET info = jsonb_set(info, '{geometry,coordinates}', $1) WHERE id = $2",
values: [coords, userid]
}
pool.query(queryOpts).then(response => {
console.log(response.rows)
}).catch(error => {
console.log(error)
})

选择查询

var email = JSON.stringify(logins.email);
const queryOpts = {
text: "SELECT * FROM users WHERE info -> 'email'=$1",
values: [email]
}
pool.query(queryOpts).then(response => {
console.log(response.rows)
}).catch(error => {
console.log(error)
})