我正在使用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会尝试运行另外两个查询?我该如何克服这个问题?
我发现了这个问题。我有两条路 - /motivations/:id
和/motivations/random
。但是,我忘了在/:id
上添加一个数字检查,因为每当我调用/random
时服务器也调用/:id
但没有给出任何参数。在我改变了/motivations/:id([0-9]+)
的路径后,问题就消失了。事实证明,对数据库的查询从一开始就有效...