基于Mongoose的应用程序架构

f1n*_*1nn 24 architecture mongoose mongodb node.js

这不是一个具体的应用程序/代码问题,它只是常见的应用程序架构.

我正在尝试理解组织我的猫鼬应用程序的正确方法.因为我是猫鼬的新手,我现在就是这样做的:

核心/ settings.js

var mongoose = require('mongoose');
exports.mongoose = mongoose;
mongoose.connect('mongodb://localhost/blog');
exports.db = mongoose.connection;
Run Code Online (Sandbox Code Playgroud)

核心/ models.js

settings = require("./settings");

// post schema
var postSchema = settings.mongoose.Schema({
    header: String,
    author: String,
    text: String
})

//compiling our schema into a Model 
exports.post = settings.mongoose.model('post', postSchema)
Run Code Online (Sandbox Code Playgroud)

芯/ DB-layer.js

settings = require("./core/settings");
models = require("./core/models");

exports.function = createAndWriteNewPost(function(callback) {
    settings.db.on('error', console.error.bind(console, 'connection error:'));
    settings.db.once('open', function callback() {
        new models.post({
            header: 'header',
            author: "author",
            text: "Hello"
        }).save(function(err, post) {
            callback('ok');
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

路线/ post.js

db = reqiure("../core/db.js")

exports.get = function(req, res) {
    db.createAndWriteNewPost(function(status){
    res.render('add_material', {
      //blah blah blah        
        });
    });
};
Run Code Online (Sandbox Code Playgroud)

app.js

var post = require ('routes/post.js')
...
app.get('/post', post.get);
Run Code Online (Sandbox Code Playgroud)

所以,这个代码非常简化(甚至没有经过测试)只是为了展示我当前的架构思想.它不是一个具体的应用程序,只是创建一个抽象的博客文章.这就是它的工作原理:

app.js --> routes/post.js <--> core/db-layer.js
                                   |
                                   v
                               core/models.js <--> core/settings.js
Run Code Online (Sandbox Code Playgroud)

对我来说似乎有点过分了.你能建议更优化的应用结构吗?谢谢.

nev*_*_me 68

当我第一次进入Node.js,Express和Mongoose时,我一直在努力扩展我的代码.我的回答是帮助那些不仅仅是一个简单的博客,而是帮助一个更大的可扩展项目的人.

  • 我总是连接到数据库,我不打开并在需要时关闭连接
  • index.js用作文件夹的根文件,就像我们在其他语言中一样
  • 模型保存在自己的文档中,并require()进入models/index.js文件.
  • 路由类似于模型,每个路由级别都有一个文件夹,该文件夹index.js依次有一个文件.因此很容易安排类似的东西http://example.com/api/documents/:id.当一个人通过文件结构时,它也更有意义.

这是我使用的结构:

-- app.js
-- models/
---- index.js
---- blog.js
-- mongoose/
---- index.js
-- routes/
---- index.js
---- blog/index.js
-- public/
-- views/
---- index.{your layout engine} => I use Jade.lang
-- methods/
---- index.js => use if you'd rather write all your functions here
---- blog.js => can store more complex logic here
Run Code Online (Sandbox Code Playgroud)

app.js

var db = require('./mongoose'),
  express = require('express');
// note that I'm leaving out the other things like 'http' or 'path'
var app = express();

// get the routes
require('./routes')(app);
// I just require routes, without naming it as a var, & that I pass (app)
Run Code Online (Sandbox Code Playgroud)

猫鼬/ index.js

// Mongoose connect is called once by the app.js & connection established
// No need to include it elsewhere
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/blog');

// I have just connected, and I'm not exporting anything from here
Run Code Online (Sandbox Code Playgroud)

车型/ index.js

// Logic here is to keep a good reference of what's used

// models
Blog = require('./blog');
// User = require('./user');

// exports
exports.blogModel = Blog.blogModel;
// exports.userModel = User.userModel;
Run Code Online (Sandbox Code Playgroud)

车型/ blog.js

因此,对于您处理的每个模型,您都要创建一个model.js文档,并在models/index.js上面添加它.作为一个例子,我添加了一个User模型,但评论了它.

// set up mongoose
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;

var BlogSchema = Schema({
  header: {type: String },
  author: {type: String },
  text: {type: String },
  _id: { type: ObjectId } // not necessary, showing use of ObjectId
});

Blog = mongoose.model('Blog', BlogSchema);
// the above is necessary as you might have embedded schemas which you don't export

exports.blogModel = Blog;
Run Code Online (Sandbox Code Playgroud)

路线/ index.js

module.exports = function(app) {
  app.get('/', function(req, res) {
    // do stuff
  });
  require('./blog')(app);
  // other routes entered here as require(route)(app);
  // we basically pass 'app' around to each route
}
Run Code Online (Sandbox Code Playgroud)

路线/博客/ index.js

module.exports = function(app) {
  app.get('/blog', function(req, res) {
    // do stuff
  });
  require('./nested')(app);
  // this is for things like http://example.com/blog/nested
  // you would follow the same logic as in 'routes/index.js' at a nested level
}
Run Code Online (Sandbox Code Playgroud)

建议使用

  • models:用于创建处理文档的逻辑,即创建,更新,删除和搜索.
  • 路由:最小编码,只需要解析http数据,创建模型实例,然后我将查询发送到相关模型.
  • 方法:用于不直接涉及模型的更复杂的逻辑.作为一个例子,我有一个algorithms/文件夹,我存储我在我的应用程序中使用的所有算法.

希望这提供更清晰.这个结构对我来说很有意义,因为我觉得很容易理解.


Mun*_*nim 9

这就是我如何去做,有一些区别:

  • 我不认为您可以在db-layer中的函数内部使用open侦听器.当我使用像你这样的持久连接时,我通常会做的是在db open handler中启动应用程序本身.如果您不想使用持久连接,请在db layer函数中使用createConnection,并确保在调用回调之前将其关闭.我不确定我是否清楚自己.如果您想要一个代码示例,请告诉我.
  • 这更像是一个通用的node.js提示,但我将数据库连接字符串和其他配置保存在json文件中,并在需要的地方需要它.之后你可能不需要另外的settings.js文件.
  • 您还可以使用模式函数(http://mongoosejs.com/docs/api.html#schema_Schema-method)将某些应用程序功能编码到模型中.

  • 我发现你的第3点非常有帮助.您是否介意在db open handler中共享一些用于启动应用程序的代码? (2认同)