Connecting your database might sound simple, “paste the URI and go,” right?
However, as your app grows, a sloppy connection setup can lead to timeouts, hanging requests, or silent disconnections.
Let’s fix that from the start.
What You’ll Learn
How to connect Node.js with MongoDB (via Mongoose)
How to connect Node.js with PostgreSQL (via
pg)Proper async setup
Handle errors, timeouts, and disconnects
Write connection code you can actually reuse in production
MongoDB Connection (with Mongoose)
Mongoose is the go-to library for Node.js + MongoDB. It simplifies schema management and handles async connections.
1 Install dependencies
npm install mongoose
2 Create a connection file
Let’s call it db/mongo.js
import mongoose from "mongoose";
const MONGO_URI = process.env.MONGO_URI || "mongodb://localhost:27017/myapp";
export async function connectMongo() {
try {
// Set connection options
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000, // Timeout after 5s
};
await mongoose.connect(MONGO_URI, options);
console.log("✅ MongoDB connected successfully");
} catch (err) {
console.error("❌ MongoDB connection error:", err.message);
process.exit(1);
}
// Handle runtime errors
mongoose.connection.on("error", (err) => {
console.error("⚠️ MongoDB connection error:", err);
});
mongoose.connection.on("disconnected", () => {
console.warn("🔌 MongoDB disconnected");
});
}
3 Use it in your app
import express from "express";
import { connectMongo } from "./db/mongo.js";
const app = express();
await connectMongo();
app.listen(3000, () => console.log("🚀 Server running on port 3000"));
PostgreSQL Connection (with pg)
PostgreSQL uses the official pg package. Simple and solid.
1 Install dependencies
npm install pg
2 Create a connection file
db/postgres.js
import pkg from "pg";
const { Pool } = pkg;
const POSTGRES_URI = process.env.POSTGRES_URI || "postgresql://user:password@localhost:5432/myapp";
const pool = new Pool({
connectionString: POSTGRES_URI,
idleTimeoutMillis: 5000, // Close idle clients after 5s
connectionTimeoutMillis: 5000, // Timeout after 5s if cannot connect
});
pool.on("connect", () => console.log("✅ PostgreSQL connected successfully"));
pool.on("error", (err) => {
console.error("❌ Unexpected PostgreSQL error:", err);
process.exit(-1);
});
export async function query(text, params) {
const client = await pool.connect();
try {
const res = await client.query(text, params);
return res;
} catch (err) {
console.error("⚠️ Query error:", err.message);
throw err;
} finally {
client.release();
}
}
3 Use it in your app
import express from "express";
import { query } from "./db/postgres.js";
const app = express();
app.get("/", async (req, res) => {
const result = await query("SELECT NOW()");
res.send(result.rows);
});
app.listen(3000, () => console.log("🚀 Server running on port 3000"));
Quick Tips
Always wrap connections in async functions
Use env variables for credentials never hardcode them
Add timeouts so your app doesn’t hang forever
Use event listeners (
on('error'),on('disconnected')) to handle runtime issuesFor real projects, add a reconnection logic if needed
Example .env file
MONGO_URI=mongodb://localhost:27017/myapp
POSTGRES_URI=postgresql://user:password@localhost:5432/myapp
Wrap-Up
Connecting to a database isn’t just about making it work. It’s about ensuring stability, so your app remains operational even when the database restarts or the network experiences hiccups.
Top comments (0)