12/04/2026 18:16pm

JS2GO EP.44 Connecting to SQL & NoSQL Databases in JavaScript and Go
#Database Connection
#Go
#JavaScript
#Node.js
#PostgreSQL
A reliable database connection is the backbone of every backend system whether it's an API, microservice, real-time server, or enterprise-grade platform.
In this EP.44, we will walk through:
✅ Databases Covered
- PostgreSQL
- MySQL
- MongoDB (NoSQL)
- Redis (In-memory / Cache / Queue / PubSub)
✅ Languages & Frameworks Used
- Node.js (Express)
- Go (Fiber)
✅ Production-Level Essentials
- Connection Pooling
- ORM / Query Builder recommendations
- Timeout / Retry / Circuit Breaker patterns
- Preventing connection leaks
- Health checks & monitoring strategies
This guide is designed to be clear, practical, and production-ready not just code snippets, but patterns used in real large-scale systems.
⭐ 1) Connecting to SQL Databases (PostgreSQL / MySQL)
Relational databases remain the foundation of most systems. PostgreSQL and MySQL are the two most popular and powerful choices today.
🟦 Go (Fiber) → PostgreSQL using pgx (Highly Recommended)
pgx is one of the fastest and most feature-rich PostgreSQL drivers in Go supporting connection pooling, cancellation, statement caching, and proper timeout handling.
➤ Connect to the Database
import (
"context"
"github.com/jackc/pgx/v5/pgxpool"
"log"
)
var DB *pgxpool.Pool
func ConnectDB() {
connStr := "postgres://user:password@localhost:5432/mydb"
pool, err := pgxpool.New(context.Background(), connStr)
if err != nil {
log.Fatal("❌ Unable to connect to database:", err)
}
DB = pool
log.Println("✅ Connected to PostgreSQL")
}
➤ Query inside a Fiber Handler
func GetUsers(c *fiber.Ctx) error {
rows, err := DB.Query(context.Background(), "SELECT id, name FROM users")
if err != nil {
return c.Status(500).SendString("DB Error")
}
defer rows.Close()
var users []User
for rows.Next() {
var u User
if err := rows.Scan(&u.ID, &u.Name); err != nil {
return c.Status(500).SendString("Scan error")
}
users = append(users, u)
}
return c.JSON(users)
}
✔ Strengths of Go + pgx
- Extremely fast (high throughput)
- Low memory footprint
- High-concurrency friendly
- Hard to cause connection leaks if used correctly
🟧 Node.js (Express) → PostgreSQL using pg
The standard library for PostgreSQL in Node.js with built-in pooling.
➤ Connect
const { Pool } = require("pg");
const pool = new Pool({
connectionString: "postgres://user:password@localhost:5432/mydb",
});
➤ Query
app.get("/users", async (req, res) => {
try {
const result = await pool.query("SELECT id, name FROM users");
res.json(result.rows);
} catch (err) {
res.status(500).send("DB Error");
}
});
⭐ 2) Connecting to MySQL
🟦 Go → MySQL using go-sql-driver/mysql
import "database/sql"
import _ "github.com/go-sql-driver/mysql"
db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/mydb")
🟧 Node.js → MySQL2 (Recommended)
import mysql from "mysql2/promise";
const pool = mysql.createPool({
host: "localhost",
user: "root",
database: "mydb",
});
⭐ 3) Connecting to MongoDB (NoSQL)
Ideal for flexible schema, high-volume datasets, and document-based design.
🟦 Go → MongoDB using the official mongo-driver
client, err := mongo.Connect(
context.Background(),
options.Client().ApplyURI("mongodb://localhost:27017"),
)
collection := client.Database("mydb").Collection("users")
🟧 Node.js → MongoDB using Mongoose (Most Popular)
import mongoose from "mongoose";
mongoose.connect("mongodb://localhost:27017/mydb");
const User = mongoose.model("User", new mongoose.Schema({
name: String
}));
⭐ 4) Connecting to Redis (Cache / Queue / PubSub / Rate Limit)
🟦 Go → Redis using go-redis v9
import "github.com/redis/go-redis/v9"
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
rdb.Set(ctx, "key", "value", 0)
🟧 Node.js → Redis using ioredis
import Redis from "ioredis";
const redis = new Redis();
await redis.set("key", "value");
⭐ 5) ORM / Query Builder Recommendations
🟦 Go ORMs / Query Tools
| Library | Strength |
|---|---|
| GORM | Easiest to use, beginner-friendly |
| SQLC | Compile-time type-safe, extremely fast |
| Ent | Schema-first, reduces human error |
| pgx | Fastest raw approach |
Recommended:
- Performance-critical → pgx
- Type-safe systems → SQLC
- Ease of development → GORM
🟧 Node.js ORM / Query Tools
| Library | Strength |
|---|---|
| Prisma | Best DX, type-safe |
| Sequelize | Long-time standard ORM |
| TypeORM | Excellent for NestJS |
| Knex.js | Lightweight, performant Query Builder |
Recommended:
- Strong type-safety → Prisma
- High performance → Knex.js
⭐ 6) Connection Pooling The Most Important Part
🟦 Go → pgx Pool Config
poolConfig, _ := pgxpool.ParseConfig(connStr)
poolConfig.MaxConns = 20
poolConfig.MinConns = 5
poolConfig.MaxConnIdleTime = 30 * time.Second
🟧 Node.js → pg Pool
const pool = new Pool({
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
});
❗ Common Mistakes to Avoid
- ❌ Creating a new DB connection in every handler
- ❌ Storing pool instances globally without DI
- ✔ Always reuse a shared connection pool
- ✔ Inject pool into services for scaling
⭐ 7) Production Best Practices
✔ Add query timeouts
✔ Enable slow query logs
✔ Use Retry + Circuit Breaker patterns
✔ Implement /health/db (e.g., SELECT 1)
✔ Use read replicas for high traffic
✔ Tune connection pool size carefully
✔ Monitor DB metrics and latency
📌 Summary
Database connectivity is a fundamental skill for every JS developer and something Go developers must master deeply.
If configured correctly, your system will be:
🚀 Fast
🧱 Stable
🔐 Secure
🌐 Production-ready
Both Node.js and Go have powerful database ecosystems:
- Node.js: pg, Prisma, ioredis
- Go: pgx, SQLC, GORM, go-redis
Mastering these tools allows you to build backend systems at a professional level.
🔵 Next Episode EP.45 Transactions & ACID in Go and JavaScript
You'll learn:
- BEGIN / COMMIT / ROLLBACK
- ACID properties
- Handling deadlocks
- Transaction scopes
- pgx/GORM transaction patterns
- Node.js PostgreSQL transaction flows
Get ready to move from Intermediate → Advanced ⚡