我正在用Koa、TypeORM和Postgres构建一个基本的API。@Get请求中的以下查询将随机结果记录到控制台,但没有返回它。
@Get("/motivations/random")
async getRandomMotivation() {
const randomFunc = async () => {
try {
let entityManager = await Motivation.getRepository()
.createQueryBuilder()
.select("motivations.id")
.from(Motivation, "motivations")
.orderBy("RANDOM()")
.limit(1)
.getOne()
console.log("__testing: ", entityManager)
return await entityManager
}
catch (error) {
console.log("___errorrrrr: ", error)
}
}
return await randomFunc()
}当我启动服务器时,它首先返回一个ConnectionNotFoundError: Connection "default" was not found.错误,然后它实际上用所有表加载服务器和数据库。然后,调用正确的端点,将随机结果登录到控制台,并在尝试返回结果时返回以下内容:
Connected to Postgres with TypeORM
Listening on port 4000 @ 22:16
query: SELECT "motivations"."id" AS "motivations_id" FROM "motivations" "Motivation", "motivations" "motivations" ORDER BY RANDOM() ASC LIMIT 1
__testing: Motivation { id: 40 }
query: SELECT "Motivation"."id" AS "Motivation_id", "Motivation"."motivation" AS "Motivation_motivation", "Motivation"."user_id" AS "Motivation_user_id" FROM "motivations" "Motivation" WHERE ("Motivation"."id" = $1) -- PARAMETERS: [null]
query failed: SELECT "Motivation"."id" AS "Motivation_id", "Motivation"."motivation" AS "Motivation_motivation", "Motivation"."user_id" AS "Motivation_user_id" FROM "motivations" "Motivation" WHERE ("Motivation"."id" = $1) -- PARAMETERS: [null]
error: { error: invalid input syntax for integer: "NaN"
.... }如您所见,它运行随机结果查询并将其记录到控制台。然后,它使用空参数运行两个查询.
为什么TypeORM试图运行两个额外的查询?我如何克服这个问题?
发布于 2018-09-07 09:53:29
我发现了问题。我有两条路-- /motivations/:id和/motivations/random。但是,我忘记在/:id上添加数字检查,因此每当我调用/random时,服务器也在调用/:id,但没有给出任何参数。在我将路径更改为/motivations/:id([0-9]+)之后,问题就消失了。从一开始,对数据库的查询就开始工作.
https://stackoverflow.com/questions/52173335
复制相似问题