node.jssql-servernestjstypeormlocaldb

Unable to connect to SQL Server LocalDB using TypeORM


I am trying to connect to my SQL Server LocalDB using TypeORM from nodejs.

My TypeORM config looks like this:

import { DataSourceOptions, DataSource } from 'typeorm';

export const dataSourceOptions: DataSourceOptions = {
  type: 'mssql',
  host: '(LocalDB)\\MSSQLLocalDB',
  database: 'TestDb',
  synchronize: false,
  logging: true,
  options: {
    trustServerCertificate: true,
  },
  entities: ['dist/persistence/entities/*.entity{ .ts,.js}'],
  migrations: ['dist/persistence/migrations/*{.ts,.js}'],
  migrationsTableName: '_DbMigrations',
  migrationsRun: true,
};

const dataSource = new DataSource(dataSourceOptions);
export default dataSource;

But on starting nodejs, I am getting this error:

[Nest] 37892 - 03/09/2024, 10:33:30 PM ERROR [TypeOrmModule] Unable to connect to the database. Retrying (2)...
ConnectionError: getaddrinfo ENOTFOUND (localdb)


Solution

  • The (localdb) syntax is not a valid hostname for connecting to a SQL Server LocalDB instance. Instead, you should use the actual machine name or IP address where your LocalDB instance is running. If you’re running LocalDB on the same machine where your Node.js application is running, you can use localhost or 127.0.0.1 as the host.