Q1. How do you connect Express to a database?
Install the appropriate database driver (e.g., mongodb, mysql2, pg for PostgreSQL).
Then create a connection in your app.
For MongoDB with Mongoose, you'd do:
For SQL, you create a connection pool.
Then create a connection in your app.
For MongoDB with Mongoose, you'd do:
mongoose.connect('mongodb://localhost/mydb').For SQL, you create a connection pool.
Q2. What are the popular databases used with Express?
MongoDB (NoSQL) is very popular with Express (MEAN/MEVN stack).
Also common: PostgreSQL, MySQL (SQL databases), Redis (caching/sessions), and Firebase.
The choice depends on your application's data structure and scalability needs.
Also common: PostgreSQL, MySQL (SQL databases), Redis (caching/sessions), and Firebase.
The choice depends on your application's data structure and scalability needs.
Q3. Should you connect to the database on every request?
No, that's inefficient.
You establish a connection once when the server starts and reuse it.
For SQL databases, you typically create a connection pool.
For Mongoose, you connect once and the connection is reused.
You establish a connection once when the server starts and reuse it.
For SQL databases, you typically create a connection pool.
For Mongoose, you connect once and the connection is reused.
Q4. How do you handle database errors in Express?
Wrap database operations in try-catch blocks (async/await) or use
Pass errors to Express error-handling middleware using
Example:
This prevents crashes.
.catch() for promises.Pass errors to Express error-handling middleware using
next(err).Example:
try { await User.find() } catch(err) { next(err) }.This prevents crashes.
Q5. What is connection pooling?
Connection pooling maintains a cache of database connections that can be reused.
Creating a new connection for each request is expensive.
A pool manages multiple connections, reducing overhead.
Most database drivers for Express support pooling.
Creating a new connection for each request is expensive.
A pool manages multiple connections, reducing overhead.
Most database drivers for Express support pooling.
