Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7615719
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T02:42:41+00:00 2026-05-31T02:42:41+00:00

I have noticed when one creates a project using Express.js, the route handler functions

  • 0

I have noticed when one creates a project using Express.js, the route handler functions are now separated from the main ‘app.js’ file. They are now placed in ‘./routes/index.js’. Given this situation, how does one now save a record to the database (in this case using MongoDB accessed via Mongoose).

Traditionally one would have had the route handler function in ‘app.js’, for example:

//Create document 
app.post('/documents.:format?', function(req, res) {
  var d = new Document(req.body);
  d.user_id = req.currentUser.id;
  d.save(function() {
    switch (req.params.format) {
      case 'json':
        var data = d.toObject();
        // TODO: Backbone requires 'id', but can I alias it?
        data.id = data._id;
        res.send(data);
      break;

      default:
        req.flash('info', 'Document created');
        res.redirect('/documents');
    }
  });
});

Under the new “layout” such call would be changed to something like the following (in ‘app.js’ file):

app.post('/documents.:format?', routes.add_documents);

With all the actual processing occurring in the file ‘./route/index.js’:

exports.add_documents = function(req, res){
  // Processing goes here!
};

My question is how can one incorporate the original route handler function into this new add_documents function above? In particular, how can one access the database schema model (e.g. create new instance of ‘Document’) so that I can access the database save method?

Full contents of ‘app.js’ is follows:

var express = require('express')
  , routes = require('./routes')
  , mongoose = require('mongoose')
  , models = require('./models')
  , Document;

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  app.set('db-uri', 'mongodb://localhost/namecards');
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

models.defineModels(mongoose, function() {
  app.Document = Document = mongoose.model('Document');
  db = mongoose.connect(app.set('db-uri'));
})

// Routes

app.get('/', routes.index);

app.get('/add', routes.add_form);

app.post('/add', routes.add_document);

app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

Content of ‘models.js’

function defineModels(mongoose, fn) {
  var Schema = mongoose.Schema,
      ObjectId = Schema.ObjectId;

  /**
   * Model: Document
   */
  Document = new Schema({
    'surname': String,
    'given_name': String,
    'org': String,
    'phone': String
  });

  mongoose.model('Document', Document);

  fn();
}

exports.defineModels = defineModels; 

Content of ‘./routes/index.js’

/*
 * GET home page.
 */

exports.index = function(req, res){
  res.render('index', { title: 'Documents' });
};

/*
 * GET add contact page.
 */
exports.add_form = function(req, res){
  res.render('add', { title: 'Add Document' });
};

/*
 * POST add contact page.
 */
exports.add_document = function(req, res){
  // Save data to DB using mongoose.
};
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T02:42:42+00:00Added an answer on May 31, 2026 at 2:42 am

    I found a method that appears to work, which doesn’t involve a huge number of changes to the code originally generated by Express. All you have to do is import mongoose into the file containing the route handler functions a.k.a. the controllers, and then load the relevant model in the routing function (see exports.addProcess below).

    Here is the modified contents of ‘./routes/index.js’

    var mongoose = require('mongoose');
    var _ = require('underscore');
    
    
    /*
     * GET home page.
     */
    
    exports.index = function(req, res){
      res.render('index', { title: 'Documents' });
    };
    
    /*
     * POST add contact page.
     */
    exports.addProcess = function(req, res){
      var Document = mongoose.model('Document');
      var document= new Document();
      document.surname = req.body.surname;
      document.given_name = req.body.given_name;
      document.org = req.body.org;
      document.phone = req.body.phone;
      document.save(function(err) {
        res.redirect('/');
      });
    };
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have noticed some developers picking up new skills and moving from one platform
Currently I'm busy on a project using XML messaging. I have one general schema,
You must have noticed one link in yahoo.com, msn.com or other popular websites named
One thing I have noticed a lot of back and forth on is where
Background: We have a project with many modules. We're using EntityFramework 4.2 with FluentAPI
Right now I'm building a project management app in rails, here is some background
We have in one of our applications a single eclipse project that contains all
I created a multi-project template using the example from vsix.codeplex.com When I hit run,
I'm using InstallShield 2010 Premiere. I have a basic MSI project that install an
I just cloned a project from GitHub and noticed that R14 preview ADT features

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.