Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript User Authentication With Express and Mongo User Registration Adding Data to the Database

chris ingvartsen
chris ingvartsen
Courses Plus Student 52 Points

Best practice for CRUD requests with Express on large applications?

Hi, in this tutorial series all the CRUD's are happening in index.js in the routes folder. I imagine this file getting really large if i were to create a social media with a lot of post requests for example.

Would I still write all the CRUD operations in the index.js file? Or split them up somehow? Would love some intake on this! :D

1 Answer

Samuel Ferree
Samuel Ferree
31,722 Points

Look into the Express router.

You can define CRUD operations for a specific model (in MVC this is what's known as a Controller) and then add that entire router to your app in the index.js.

For example:

Create a router file named birds.js in the app directory, with the following content:

var express = require('express')
var router = express.Router()

// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
  console.log('Time: ', Date.now())
// define the home page route
router.get('/', function (req, res) {
  res.send('Birds home page')
// define the about route
router.get('/about', function (req, res) {
  res.send('About birds')

module.exports = router

Then, load the router module in the app:

var birds = require('./birds')

// ...

app.use('/birds', birds)