jeudi 30 août 2018

Selecting Random Row With Postgres & TypeORM

I am trying to get a random row from a table in Postgres.

After reading this and this I was able to come up with the following piece of code:

@Get("/motivations/random")
async getRandomMotivation() {

  return await getConnection()
    .createQueryBuilder()
    .select("id")
    .from(Motivation, "motivation")
    .orderBy("RANDOM()")
    .limit(1)
    .getOne()
}

The result is this:

query: SELECT id FROM "motivations" "motivation" ORDER BY RANDOM() ASC LIMIT 1

However, when sending a GET request with POSTMAN it returns a NotFoundError and that's all ...

I was looking in TypeORM's documentation plenty of times, looking for a randomizing solution of any sort but found none.

Did I miss anything in the query builder? Or did I add something extra? Or just the whole query statement is built in the wrong way?

Any tip or comment helping solve the problem is welcomed.




Aucun commentaire:

Enregistrer un commentaire