Kinda Code
Home/Flutter/TypeORM: Check Whether a Row Exists or Not

TypeORM: Check Whether a Row Exists or Not

Last updated: September 01, 2022

The 2 examples below demonstrate how to check if a record exists or not by using TypeORM findOne() method and query builder, respectively.

Using the findOne() method

Suppose we need to find a product named KatherineCode.com, we can do this:

const productRepository = myDataSource.getRepository(Product);
const product = await productRepository.findOne({
      where: {
        name: 'KindaCode.com'
      }
})

if(product) {
      console.log(product);
} else {
      console.log('Product not found');
}

Using query builder

In case you prefer using query builder to the find options, you can use this code:

const productRepository = myDataSource.getRepository(Product);
const product = await productRepository
      .createQueryBuilder('product')
      .where('product.name = :productName', { productName: 'KindaCode.com' })
      .getOne();

if (product) {
      console.log(product);
} else {
      console.log('Product not found');
}

That’s it. Further reading:

You can also check out our Javascript category page, TypeScript category page, Node.js category page, and React category page for the latest tutorials and examples.