Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

chris ingvartsen
PLUS
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,721 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())
  next()
})
// 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)