Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Organizing Database Code | Section
Working with MongoDB in Express Applications

bookOrganizing Database Code

Swipe to show menu

As your application grows, database-related code should be separated from routes.

A common approach is to keep models in a dedicated folder.

Example structure:

  • models/user.js: defines the schema and model;
  • routes/users.js: handles API routes.

Model file:

// models/user.js
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: String,
  age: Number
});

module.exports = mongoose.model('User', userSchema);

Route file:

// routes/users.js
const express = require('express');
const router = express.Router();
const User = require('../models/user');

router.get('/', async (req, res) => {
  const users = await User.find();
  res.json(users);
});

module.exports = router;

This separation keeps your code cleaner and easier to maintain.

question mark

Why should database code be separated from routes?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 14

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 1. Chapter 14
some-alt