Database connectivity lets your Node.js app talk to a database to save and get data. Without it, your app can't remember or use information.
Why database connectivity matters in Node.js
const { Client } = require('pg');
async function main() {
const client = new Client({
user: 'user',
host: 'localhost',
database: 'mydb',
password: 'password',
port: 5432
});
await client.connect();
// Use client to query the database
await client.end();
}
main().catch(console.error);This example uses the 'pg' library to connect to a PostgreSQL database.
You create a client with connection details, connect, run queries, then close the connection.
const mysql = require('mysql2/promise'); async function main() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root', database: 'testdb', password: 'password' }); // Run queries here await connection.end(); } main().catch(console.error);
import { MongoClient } from 'mongodb'; const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri); async function run() { await client.connect(); const database = client.db('mydb'); const collection = database.collection('users'); // Use collection to find or insert documents await client.close(); } run();
This Node.js program connects to a PostgreSQL database, asks for the current time, prints it, then closes the connection.
import { Client } from 'pg'; async function main() { const client = new Client({ user: 'user', host: 'localhost', database: 'mydb', password: 'password', port: 5432 }); await client.connect(); const res = await client.query('SELECT NOW()'); console.log('Current time from database:', res.rows[0].now); await client.end(); } main().catch(console.error);
Always close your database connection to avoid resource leaks.
Use async/await to handle database calls cleanly and avoid callback hell.
Keep your database credentials safe and do not hardcode them in real apps.
Database connectivity lets your app save and get data.
You connect, run queries, then close the connection.
It is important for apps that need to remember or update information.
Practice
Solution
Step 1: Understand the role of database connectivity
Database connectivity lets the app communicate with a database to save or get data.Step 2: Identify the importance for data persistence
Without database connectivity, the app cannot remember or update information after it stops running.Final Answer:
It allows the app to save and retrieve data persistently. -> Option BQuick Check:
Database connectivity = save and retrieve data [OK]
- Thinking it speeds up the app without data storage
- Confusing database connectivity with UI features
- Assuming it fixes code bugs automatically
Solution
Step 1: Recognize common Node.js database connection syntax
Popular libraries like mysql use require('mysql').createConnection(config) to connect.Step 2: Check each option for correct syntax
const db = require('mysql').createConnection(config); matches the correct pattern; others have wrong method calls or missing parts.Final Answer:
const db = require('mysql').createConnection(config); -> Option AQuick Check:
Correct connection syntax = const db = require('mysql').createConnection(config); [OK]
- Using connect() directly without require
- Wrong method names like connect.db
- Missing configuration object
const mysql = require('mysql');
const connection = mysql.createConnection({host: 'localhost', user: 'root', password: 'wrong'});
connection.connect(err => {
if (err) {
console.log('Connection error');
} else {
console.log('Connected');
}
});Solution
Step 1: Understand the connection callback behavior
The connect method calls the callback with an error if connection fails.Step 2: Analyze the error handling in the callback
If err exists, it logs 'Connection error'; otherwise, 'Connected'. Wrong password causes err.Final Answer:
Connection error -> Option CQuick Check:
Error in connect logs 'Connection error' [OK]
- Assuming it logs 'Connected' even on failure
- Expecting a syntax error from wrong password
- Thinking no output occurs on failure
const mysql = require('mysql');
const connection = mysql.createConnection({host: 'localhost', user: 'root', password: 'pass'});
connection.connect();
connection.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
console.log(results);
});
connection.end();Solution
Step 1: Check connection timing
connect() is asynchronous; without a callback, query may run before connection is ready.Step 2: Identify the impact on query execution
Running query before connection is established can cause errors or unexpected behavior.Final Answer:
Missing callback in connect() causes query to run before connection is ready. -> Option DQuick Check:
connect() async needs callback before query [OK]
- Calling end() too early before queries finish
- Thinking createConnection needs a callback
- Misusing query() parameters
Solution
Step 1: Consider connection efficiency and data consistency
Reusing one connection reduces overhead and keeps queries consistent.Step 2: Evaluate options for frequent updates
Opening and closing connections for each query wastes resources; in-memory storage loses data on restart.Final Answer:
Connect to the database once at app start, reuse connection for all queries, and close on app exit. -> Option AQuick Check:
Reuse connection for frequent updates [OK]
- Opening/closing connection for every query wastes resources
- Not using database loses persistent data
- Using DB only for reads misses updates
Ready to prove it?
Pass the test and this pattern moves unknown
