Explore Related Tools
Hand-picked utilities and calculators related to this tool.
Express doesn't care which database you use. However, there are established best practices for organizing your database logic.
Always separate your database schemas and logic from your route handlers.
// models/User.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({ ... });
module.exports = mongoose.model('User', userSchema);Connect to the database before starting the Express server.
const mongoose = require('mongoose');
const app = require('./app');
mongoose.connect(process.env.DB_URI)
.then(() => {
app.listen(3000, () => console.log('DB Connected & Server Running'));
});In a large Express app, use Controllers to handle the interaction between Routes and Models.
// controllers/userController.js
exports.getAllUsers = async (req, res) => {
const users = await User.find();
res.json(users);
};express-async-errors or a custom catchAsyncutility to avoid wrapping every database call in a try/catch block.Hand-picked utilities and calculators related to this tool.
