【问题标题】:Mongoose-based app architecture基于 Mongoose 的应用架构
【发布时间】:2013-03-05 11:14:17
【问题描述】:

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

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

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 mongodb architecture mongoose


【解决方案1】:

当我第一次接触 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)

猫鼬/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/ 文件夹,用于存储我在应用中使用的所有算法。

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

【讨论】:

  • @nevi-me,你能告诉我,我如何在 routes/blog/index.js 中使用 bogModel 来查找?
  • @Rashid 您必须编写为您搜索数据库的逻辑。搜索模式和方法,因为您将使用它们与模型中的数据库进行交互。所以逻辑应该写在/models/Blog.js(或等效)中我认为Google上的一个简单的Mongoose教程就足够了
  • @nevi_me 我是一个新手,我很困惑,如何在路线中获得猫鼬连接。请帮忙。
  • @RajatSaxena 请分享您的代码,以便我们提供帮助
  • @nevi_me 我自己解决了。但我有一个疑问,这一行Blog = mongoose.model('Blog', BlogSchema);,在这里,Blog 将被导出到全局命名空间还是什么?因为当我在Blog 之前添加let/var 时,我的代码开始抛出Blog is not defined 错误。
【解决方案2】:

这就是我的做法,但有一些不同:

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

【讨论】:

  • 我发现你的第三点很有帮助。您介意分享一些在 db open 处理程序中启动应用程序的代码吗?
猜你喜欢
  • 2011-09-14
  • 1970-01-01
  • 2012-05-28
  • 2018-01-28
  • 1970-01-01
  • 2011-01-20
  • 2014-12-15
  • 2011-02-23
  • 2015-12-23
相关资源
最近更新 更多