2012-03-07 89 views
0

我注意到,當使用Express.js創建項目時,路由處理函數現在與主'app.js'文件分離。他們現在被放置在'./routes/index.js'中。鑑於這種情況,現在如何將一條記錄保存到數據庫(在這種情況下使用通過Mongoose訪問的MongoDB)。從路由處理函數中訪問數據庫模型的保存方法的正確方法是什麼?

傳統一個將不得不在「app.js」的路由處理功能,例如:

//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'); 
    } 
    }); 
}); 

根據新的「佈局」這樣的通話將被更改爲類似(以下在「應用程序的.js'文件):

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

隨着發生的文件中的所有實際處理」 ./route/index.js':

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

我的問題是如何將原始路由處理函數合併到上面的這個新的add_documents函數中?特別是,如何訪問數據庫模式模型(例如,創建'Document'的新實例),以便我可以訪問數據庫保存方法?

'app.js' 是的全部內容如下:的 '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; 

內容

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); 

內容」 ./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. 
}; 

回答

0

我發現,似乎工作的方法,它不涉及Express最初生成的代碼發生大量更改。您只需將mongoose導入包含路由處理函數a.k.a.控制器的文件中,然後在路由功能中加載相關模型(請參見下面的exports.addProcess)。

這裏是」 ./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

我通常稱這個控制器遵循MVC。

我將導入我的模型/架構到控制器

以下是我該怎麼做MVC中的節點/表達

//controller 

module.exports = function (app, models) { 
    var ctrl = { 
    add_documents: function(req, res) { 
     var document = new models.Document(); 
     document.something = something; 
     document.save(); 
     res.end("Saved"); 
    } 
    return crtl; 
} 

//sample model 
module.exports = function(mongoose) { 
var Document = new mongoose.Schema({ 
    field: value 
}); 
var model = mongoose.model('Document', Document); 
return model; 
} 


//model loader 
module.exports = function(app, mongoose) { 
mongooseTypes = require("mongoose-types"); 
mongooseTypes.loadTypes(mongoose); 
var obj = { 
    Document: require('./models/document.js')(mongoose) 
} 
return obj; 
} 

//app.js 
var mongoose = require('mongoose'); 
var models = require('./models')(app, mongoose); 
var routes = require('./routes')(app, models); 

//routes 
module.exports = function(app, models) { 
    var DocumentController = require("./controllers/documents")(app, models); 
    app.post('/documents:.format', DocumentController.add_documents); 
} 
+0

感謝您的快速響應修改的內容。將模型傳遞給「控制器」是有意義的。我有點困惑於如何在這裏實現你的解決方案。控制器代碼在哪裏?控制器文件中的 – Benjen 2012-03-07 09:10:29

+0

。 – 2012-03-07 09:22:40

+0

// routes module.exports = function(app,models)var DocumentController = require(「./ controllers/documents」)(app,models); app.post('/ documents:.format',DocumentController.add_documents); } – 2012-03-07 09:23:38

相關問題