node.js - 基于 Mongoose 的应用架构

标签 node.js mongodb architecture mongoose

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

我正在尝试了解码织我的 Mongoose 应用程序的正确方法。由于我是 Mongoose 的新手,所以我现在就是这样做的:

core/settings.js

var mongoose = require('mongoose');
exports.mongoose = mongoose;
mongoose.connect('mongodb://localhost/blog');
exports.db = mongoose.connection;

core/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)

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

routes/post.js

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

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

app.js

var post = require ('routes/post.js')
...
app.get('/post', post.get);

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

app.js --> routes/post.js <--> core/db-layer.js
                                   |
                                   v
                               core/models.js <--> core/settings.js

这对我来说似乎有点多余。你能建议更优化的应用程序结构吗?谢谢。

最佳答案

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

  • 我始终连接到数据库,我不会在需要时打开和关闭连接
  • 我使用 index.js 作为文件夹的根文件,就像我们在其他语言中所做的那样
  • 模型保存在自己的文档中,require()d 到 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

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)

Mongoose /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

models/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;

models/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;

routes/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
}

routes/blog/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
}

建议使用

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

希望这可以提供更清晰的信息。这种结构对我来说非常有用,因为我发现它很容易理解。

关于node.js - 基于 Mongoose 的应用架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15454441/

相关文章:

node.js - 如何使用他们的 sdk 在 AWS S3 中移动(而不是复制)文件?

javascript - 从 AS3 客户端运行 MongoDB 查询?

javascript - 从 mongodb 创建项目数组 - Node js

ruby-on-rails - 设置 Elasticsearch 服务器以处理来自微服务的数据

javascript - currentUser 显示为未定义

javascript - 在循环中获取数据

javascript - 使用 webpack 的 require.ensure 函数为 javascript 模块编写测试

node.js - 为什么 Mongo 给这个字段分配一个 id?

architecture - 使用单个 HTTP/2 连接进行双向(和对称)通信

.net - 在 .NET Web 应用程序中实现不受信任的插件