我在这里采取了另一种方法。不是说这是最好的,而是让我解释一下。
- 每个模式(和模型)都在其自己的文件(模块)中
- 特定REST资源的每组路由都在各自的文件(模块)中
- 每个路由模块只是
require
其所需的Mongoose模型(仅1个) - 主文件(应用程序入口点)仅
require
是所有路由模块的注册对象。 - Mongo连接位于根文件中,并作为参数传递给任何需要的连接。
我的应用程序根目录下有两个子文件夹-
routes和
schemas。
这种方法的好处是:
- 您只需编写一次架构。
- 您不会使用每个REST资源(CRUD)的4-5条路由的路由注册来污染您的主应用程序文件
- 您只需定义一次数据库连接
这是特定模式文件的外观:
文件:/schemas/theaterSchema.js
module.exports = function(db) { return db.model('Theater', TheaterSchema());}function TheaterSchema () { var Schema = require('mongoose').Schema; return new Schema({ title: { type: String, required: true }, description: { type: String, required: true }, address: { type: String, required: true }, latitude: { type: Number, required: false }, longitude: { type: Number, required: false }, phone: { type: String, required: false } });}这是特定资源的路由集合的外观:
文件:/routes/theaters.js
module.exports = function (app, options) { var mongoose = options.mongoose; var Schema = options.mongoose.Schema; var db = options.db; var TheaterModel = require('../schemas/theaterSchema')(db); app.get('/api/theaters', function (req, res) { var qSkip = req.query.skip; var qTake = req.query.take; var qSort = req.query.sort; var qFilter = req.query.filter; return TheaterModel.find().sort(qSort).skip(qSkip).limit(qTake) .exec(function (err, theaters) { // more pre }); }); app.post('/api/theaters', function (req, res) { var theater; theater.save(function (err) { // more pre }); return res.send(theater); }); app.get('/api/theaters/:id', function (req, res) { return TheaterModel.findById(req.params.id, function (err, theater) { // more pre }); }); app.put('/api/theaters/:id', function (req, res) { return TheaterModel.findById(req.params.id, function (err, theater) { // more pre }); }); app.delete('/api/theaters/:id', function (req, res) { return TheaterModel.findById(req.params.id, function (err, theater) { return theater.remove(function (err) { // more pre }); }); });};这是根应用程序文件,该文件初始化了连接并注册了所有路由:
文件:app.js
var application_root = __dirname, express = require('express'), path = require('path'), mongoose = require('mongoose'), http = require('http');var app = express();var dbProduction = mongoose.createConnection('mongodb://here_insert_the_mongo_connection_string');app.configure(function () { app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(application_root, "public"))); app.use('/images/tmb', express.static(path.join(application_root, "images/tmb"))); app.use('/images/plays', express.static(path.join(application_root, "images/plays"))); app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));});app.get('/api', function (req, res) { res.send('API is running');});var theatersApi = require('./routes/theaters')(app, { 'mongoose': mongoose, 'db': dbProduction });// more preapp.listen(4242);希望这会有所帮助。



