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