我正在尝试使用Postgresql和Knex在Node中设置基本数据库连接,但是我无法获得看似简单的插入工作。我将大部分代码基于Knex github repo中的示例代码。
问题似乎是我的第一个插入(我添加管理员用户)是解析一组空行(不太确定,因为文档不包含行或行集的任何信息,尽我所能找到)。
这是我的代码:
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));
}
非常感谢任何帮助。
答案 0 :(得分:3)
Promise处理程序必须返回一些东西。它像装配线一样工作 - 每个工作站必须将其工作结果重新放到生产线上。
.returning()
(docs)。console.log.bind(console)
)什么都不返回,因此链的最终结果是未定义的。Promise.resolve()
启动承诺链。您可以使用任何承诺返回功能启动它 - 直接使用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;
});
}