这是执行查询的路径:
userRouter.route("/new")
.post(function (req, res) {
var user = req.body;
pg.connect(connectionString, function (error, client, done) {
var queryString = "INSERT INTO Users (id, first_name, last_name) VALUES (" + "'" + [user.id, user.first_name, user.last_name].join("','") + "'" + ")";
console.log(queryString);
client.query(queryString, function (error, result) {
console.log(result.rows);
done();
});
});
});
问题是我试图从第二个控制台中引用的“结果”值基本上是空白的:
{
command: 'INSERT',
rowCount: 1,
oid: 0,
rows: [],
fields: [],
_parsers: [],
RowCtor: null,
rowAsArray: false,
_getTypeParser: [Function: bound ]
}
result.rows 不应该包含一个数组,其中包含一个表示我刚刚在数据库中创建的行的对象吗?
最佳答案
好的,我已经弄清楚了。
显然,我试图使用一个尚未在 Node-Postgres 中实现的功能,如下所述:https://github.com/brianc/node-postgres/wiki/Todo
在查询结果回调中插入/更新/选择行数
Though this would be extremely awesome off course, it is possible to obtain the behaviour by adding RETURNING id or even RETURNING * to the query. This works fine for single columns for me. I will test this for multiples and the handling of that case by this package. I am quite certain it must be possible in postgres.
因此,我更新了查询以返回新行的所有数据:
var queryString = "INSERT INTO Users (first_name, last_name) VALUES (" + "'" + [user.first_name, user.last_name].join("','") + "'" + ") RETURNING *";
然后我修改了查询以说明“行”事件处理程序,该处理程序在将新行输入数据库时触发。在这个事件处理程序的上下文中,我可以访问新的行数据(根据上面的“RETURNING”参数:
var query = client.query(queryString, function (error, result) {
done();
});
query.on("row", function (row, result) {
console.log("Inside the row event handler.");
res.render("users/show", { user: row });
});
啊啊啊,它起作用了!
关于javascript - Node-postgres 将新记录插入我的数据库不会返回新条目的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34966841/