如何用node.js / Express 3和Mongoose(MongoDB)组织代码/逻辑

我看到很多例子,其中node.js / express路由器代码是这样组织的:

// server.js

var cats = require('cats'); app.get('/cats', cats.findAll); 

// routes / cats.js

 exports.findAll = function(req, res) { // Lookup all the cats in Mongoose CatModel. }; 

我很好奇,如果将逻辑创build,读取,更新和删除猫猫猫猫CatModel作为方法是没问题的? 所以你可以做一些像cat.findAll(); 模型可能看起来像这样:

 var Cat = new Schema({ name: { type: String, required: true } }); Cat.methods.findAll = function(callback) { // find all cats. callback(results); } 

那么你可以在你的路由器中使用它:

 app.get('/cats', cats.findAll); 

如果需要进一步的逻辑/抽象(处理结果),那么可以使用routes/cats.js

提前致谢。

显然你的架构完全取决于你。 我发现分开我的路线(处理业务逻辑)和模型(与数据库交互)是非常必要和非常容易的。

所以我通常会有类似的东西

app.js

 var cats = require ('./routes/cats'); app.get('/api/cats', cats.getCats); 

路线/ cats.js

 var Cats = require ('../lib/Cats'); exports.getCats = function (req, res, next) { Cat.get (req.query, function (err, cats) { if (err) return next (err); return res.send ({ status: "200", responseType: "array", response: cats }); }); }; 

LIB / Cat.js

 var catSchema = new Schema({ name: { type: String, required: true } }); var Cat = mongoose.model ('Cat', catSchema); module.exports = Cat; Cat.get = function (params, cb) { var query = Cat.find (params); query.exec (function (err, cats) { if (err) return cb (err); cb (undefined, cats); }); }; 

所以这个例子并没有显示出优势,但是如果你有一个addCat路由,那么这个路由可以使用一个“getCatById”函数调用,validation这个cat不存在并添加它。 它也有助于一些嵌套。 这些路由也可以在发送它们之前用于消毒对象,还可以发送UI中使用的资源和信息,这些资源和信息不一定与mongoose相连。 它还允许与数据库的交互可以在多个路由中重用。