Knex在插入后parsing空集

我试图在Node中使用Postgresql和Knex设置一个基本的数据库连接,但我很难得到一个简单的插入工作。 我将大部分代码放在Knex github库中的代码示例中。

这个问题似乎是我的第一个插入(我添加pipe理员用户)正在解决一个空的行集(不太确定,因为文档没有包含行或行集上的任何信息,只要我可以find)。

这是我的代码:

const knex = require("knex")({ client: "postgres", connection: { host : "127.0.0.1", user : "postgres", password : "my password goes here", database : "issue-tracker", charset : "utf8" } }); knex.schema .dropTableIfExists("tickets") .dropTableIfExists("users") .createTable("users", createUserTable) .createTable("tickets", createTicketTable) .then(() => addTestData()) .then(() => console.log("Done")) .catch((e) => console.log(e)); function createUserTable(table) { table.increments("id"); table.string("username").index().unique(); table.string("password"); table.timestamps(); } function createTicketTable(table) { table.increments("id"); table.timestamps(); table.integer("creator_id").unsigned().references("users.id"); table.string("text"); } function addTestData() { return Promise.resolve() .then(() => knex.insert({username: "admin", password: "password"}) .into("users") ) .then((rows) => // rows is empty? knex.insert({creator_id: rows[0], text: "this is a test"}) .into("tickets") ) .then(() => knex("users").join("tickets", "users.id", "tickets.creator_id") .select("users.id as creator_id", "users.username as creator_name", "tickets.text as text") ) .then(console.log.bind(console)); } 

任何援助将不胜感激。

承诺处理程序必须返回一些东西。 它像一条assembly线一样工作 – 每个工作站都必须把工作结果放回原位。

  • 在knex中插入操作不会返回行,除非你明确告诉它们。 Knex有.returning() ( docs )。
  • 链中的最后一个处理程序( console.log.bind(console) )不会返回任何内容,因此链的最终结果是未定义的。
  • 您不需要使用Promise.resolve()来启动承诺链。 你可以用任何promise- knex()函数来启动它 – 在这里直接使用knex()是明智的。

所以,稍微重新安排,我们结束了这个:

 function addTestData() { return knex("users") .returning("user_id") .insert({username: "admin", password: "password"}) .then((rows) => { return knex("tickets") .returning("ticket_id") .insert({creator_id: rows[0], text: "this is a test"}); }) .then((rows) => { return knex("users") .join("tickets", "users.id", "tickets.creator_id") .select("users.id as creator_id", "users.username as creator_name", "tickets.text as text"); }) .then((rows) => { console.log.bind(console); return rows; }); } 

这相当于这个,其中隐含的return ,因此不太明显:

 function addTestData() { return knex("users") .returning("user_id") .insert({username: "admin", password: "password"}) .then((rows) => knex("tickets") .returning("ticket_id") .insert({creator_id: rows[0], text: "this is a test"}); }) .then((rows) => knex("users") .join("tickets", "users.id", "tickets.creator_id") .select("users.id as creator_id", "users.username as creator_name", "tickets.text as text"); }) .then((rows) => { console.log.bind(console); return rows; }); }