Node.js + mongo + express MVC API: how to use controllers?

10,988

Solution 1

Well, a controller is basically an adapter between your domain code and your view code, and that's what you are accomplishing with your routing code in Express. You might want to check out this MVC example by the express people to get a better idea, and this related SO answer speaking of routes vs controllers.

On the other side of the puzzle, you'll find Angular does have a component called controllers, which ideally would delegate the server-talking aspect to other Angular components like services but are arguably not exactly the kind of controllers you're probably thinking of in a typical MVC example.

Solution 2

Assuming you're using Express 4

https://www.terlici.com/2014/09/29/express-router.html

Create an app.js such as

var express = require('express')
  , app = express()

//we're loading in our 'controllers' as middleware
app.use(require('./controllers'))

app.listen(3000, function() {
  console.log('Listening on port 3000...')
})

then in /controllers create an index.js, that looks like:

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

router.use('/person', require('./person'))

//default routes here
//these could go in a separate file if you want
router.get('/', function(req, res) {
  res.send('Home page')
})

router.get('/about', function(req, res) {
  res.send('Learn about us')
})

module.exports = router

Next, your person controller will look something like this:

var mongoose = require('mongoose'),
    Person = mongoose.model('Person'),
    express = require('express'),
    router = express.Router()

// actual url will be /person/ since we're loading this in via index.js
router.get('/', function(req, res) {
  Person.find({}, function(err, results) { return res.send(results); } );
})

router.post('/', function(req, res) {
  //save logic here
})

module.exports = router
Share:
10,988

Related videos on Youtube

MarcoS
Author by

MarcoS

I'm a sailor. I love roaming in the Mediterranean sea on any wood piece you can stick a mast and a sail on. In my spare time I do software engineering in Turin, as a full-stack developer. I start my coding ages ago with x86 assembly; then I go with C, bash, Perl, Java; Android; currently I do MEAN stack: MongoDB, Express.js, Angular.js and of course Node.js. Obviously on the shoulders of the GNU/Linux O.S..

Updated on June 04, 2022

Comments

  • MarcoS
    MarcoS over 1 year

    I'm writing my first MEAN app... To be correct, currently it is a MEN :-) app, since it's only the server-side API by now... I'd like to follow an MVC pattern (or MC, since I have no views).

    I want to choose a correct structure for my app, and I'm trying to understand how to use routes, model and controllers... In particular, it's not clear to me how to use controllers...

    The first question is this: how and where do I define my class methods?

    Currently:
    I define a 'model' in "models/person.js".
    Then, I add (class) methods in the same model file, this way:

    personSchema.method.save = function(callback) {
      this.model('Person').savefind({ type: this.type }, callback);
    }
    module.exports = mongoose.model('Person', personSchema);
    

    Then, in the routes ("routes/persons.js", for example), I require() the models I need, and implement the route methods.

    If this is a correct and common approach, I do not understand how to use controllers... :-(
    Maybe controllers are not needed in a server-side API exposing application?

    Hope someone can shed some light on my MEAN understanding... :-)

  • MarcoS
    MarcoS about 8 years
    Yes, thanks... I put the logic you put in /controllers in '/routes`... Probably my misunderstang is just this one... Thanks..
  • MarcoS
    MarcoS about 8 years
    Thanks! Yes, I did use Angular a bit, and my main idea of 'controller' was just from Angular... Thanks for the links!
  • Honinbo Shusaku
    Honinbo Shusaku over 7 years
    @Alex So in NodeJS, the controller and model are basically the same? My understanding of MVC might not be correct, but in other languages, I'd usually just create and instance of the model in the controller and then manipulate the model based on data I'm pulling from the view
  • Honinbo Shusaku
    Honinbo Shusaku over 7 years
    @Alex never mind, I understand it better after looking at this...except it's with mongoDB instead of MySQL