Search code examples
node.jsexpresstypeorm

Find one entity from database table in TypeORM


I am using TypeORM in my express.js project.

I wonder in TypeORM, how can I find an entity from database without providing any condition, I just need to get one instance from database table.

For example, I have a students table which maps to Student entity. I tried:

const student = await Student.find()[0];

But it is not working. Any suggestion?

P.S. after I found a student I need to access its id e.g. const sid = student.id

I am using the sid to construct a data as a payload for response. e.g. const payload={'student_id': sid, ...}


Solution

  • You can try using findOne method by passing empty object as argument.

    const student = await Student.findOne({})
    

    You can also use your current approach but you gotta make sure you wrap your await in parentesis before you access the array index.

    const student = (await Student.find())[0];
    

    Beware though, find() will read all of the database while findOne() will only be a single read.

    Update To avoid type issues , you can add a type guard.

    if(!student){
      // return or send error as response.
    return;
    }