我正在尝试使用Postgresql和肯奈在Node中建立一个基本的数据库连接,但我很难获得一个看似简单的插入操作。我的大部分代码都是基于中的示例代码。
问题似乎是,我的第一个insert (添加管理用户)解析了一个空行集(因为文档中没有任何关于行或行集的信息)。
这是我的代码:
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));
}如能提供任何援助,将不胜感激。
发布于 2016-09-07 16:22:47
承诺处理程序必须返回一些东西。它的工作原理就像一条装配线--每个站都必须把它的工作结果放回生产线上。
.returning() (文档)。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;
});
}https://stackoverflow.com/questions/39374802
复制相似问题