Performance: Mongoose ODM setup
This affects the initial page load speed and server response time by how the database connection and schema setup impact backend processing.
Jump into concepts and practice - no test required
const mongoose = require('mongoose'); async function connectDB() { try { await mongoose.connect('mongodb://localhost:27017/mydb'); console.log('DB connected'); } catch (err) { console.error('DB connection error', err); } } connectDB(); const userSchema = new mongoose.Schema({ name: String }); const User = mongoose.model('User', userSchema); app.get('/users', async (req, res) => { const users = await User.find(); res.json(users); });
const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: String }); const User = mongoose.model('User', userSchema); app.get('/users', async (req, res) => { await mongoose.connect('mongodb://localhost:27017/mydb'); const users = await User.find(); res.json(users); });
| Pattern | DB Connections | Server Blocking | Request Latency | Verdict |
|---|---|---|---|---|
| Connecting once at startup | 1 persistent connection | No blocking during requests | Low latency | [OK] Good |
| Connecting inside each request | Multiple repeated connections | Blocks request handling | High latency | [X] Bad |
mongoose.connect() in an Express app?dbURI?mongoose.connect(dbURI)
.then(() => console.log('DB connected'))
.catch(err => console.error('Connection error', err));mongoose.connect('mongodb://localhost:27017/mydb', () => {
console.log('Connected to DB');
}).catch(err => console.error(err));