基于 Mongoose 的应用架构 [英] Mongoose-based app architecture

查看:30
本文介绍了基于 Mongoose 的应用架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

I'm trying to understand proper way to organize my mongoose application. As I'm new to mongoose, that's how I do it now:

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

路由/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);

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

So, this code was extremely simplified (even not tested) just to show my current architecture thoughts. It's not a concrete app, just something like creating an abstract blog post. So thats how it works:

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

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

It seems a bit over superfluous for me. Could you suggest more optimal app structure? Thanks.

推荐答案

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

When I first got into Node.js, Express and Mongoose I struggled with scaling my code. The intention of my answer is to help someone who's working on more than just a simple blog, but to help with an even larger scalable project.

  • 我总是连接到数据库,我不会在需要时打开和关闭连接
  • 我使用 index.js 作为文件夹的根文件,就像我们在其他语言中所做的一样
  • 模型保存在它们自己的文档中,并且 require()d 到 models/index.js 文件中.
  • 路由和模型类似,每个路由级别都有一个文件夹,里面依次有一个index.js文件.所以很容易安排像 http://example.com/api/documents/:id 这样的东西.当您浏览文件结构时,这也更有意义.
  • I am always connected to the database, I do not open and close connections when needed
  • I use index.js as the root file of a folder, just like we'd do in other languages
  • models are kept in their own documents, and require()d into the models/index.js file.
  • routes are similar to models, each route level has a folder, which has an index.js file in turn. So it's easy to arrange something like http://example.com/api/documents/:id. It also makes more sense when one goes through the file structure.

这是我使用的结构:

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

猫鼬/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 模型,但已将其注释掉.

So for every model that you work on you create a model.js document, and add it in the models/index.js above. As an example I've added a User model but commented it out.

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

建议使用

  • 模型:用于创建处理文档的逻辑,即创建、更新、删除和搜索.
  • routes:最少的编码,只在我需要解析 http 数据、创建模型实例,然后向相关模型发送查询的地方.
  • methods:用于不直接涉及模型的更复杂的逻辑.例如,我有一个 algorithms/ 文件夹,用于存储我在应用中使用的所有算法.
  • models: for creating the logic that deals with the documents, i.e. creating, updating, deleting, and searching.
  • routes: minimal coding, only where I need to parse http data, create instances of models, and then I send queries to the relevant model.
  • methods: for the more complex logic that doesn't directly involve models. As an example, I have an algorithms/ folder where I store all the algorithms that I use in my app.

希望这能提供更清晰的信息.这种结构对我来说很神奇,因为我发现它很容易理解.

Hope this provides more clarity. This structure is working wonders for me as I find it easy to follow.

这篇关于基于 Mongoose 的应用架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆