Search code examples
node.jsnodestypeorm

Not able to access the data inside of an object


I am fetching id column value from database for a particular email. In this case I am passing email and want to get primary key i.e id. This operation is successful as I get object which contains Object with the right and expected result. However I am not able to access the object.

I am receiving object like this:

[ UserInfo { id: 21 } ]

And I am not able to access id part of it.

I am using node.js, postgres for database and typeorm library to connect with database.

    const id = await userRepo.find({
        select:["id"],
        where: {
            email:email
        }
    });

    console.log(id)
   This prints the above object.

The id I am getting is right. But I am not able to retrieve the id part of the object. I tried various ways for e.g.

id['UserInfo'].id, id.UserInfo.

Please help me in accessing the object I am receiving


Solution

  • Typeorm .find() returns an array of objects containing entries corresponding to your filters, in your case, all entries with an email field corresponding to the email you specified.

    Because the result is an array, you can access it this way:

    const records = await userRepo.find({
      select: ['id'],
      where: {
        email,
      },
    })
    console.log(records[0].id)
    

    You could also use the .findOne() method, which returns a single element and might be a better solution in your case :)