27

これは具体的なアプリ/コードの質問ではなく、一般的なアプリ アーキテクチャに関するものです。

私のマングースアプリケーションを整理する適切な方法を理解しようとしています。私はマングースが初めてなので、それが今のやり方です:

コア/settings.js

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

コア/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);

したがって、このコードは、私の現在のアーキテクチャの考えを示すために、非常に単純化されています (テストもされていません)。これは具体的なアプリではなく、抽象的なブログ投稿を作成するようなものです。それがどのように機能するかです:

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

私には少し余分なようです。より最適なアプリ構造を提案していただけますか? ありがとう。

4

2 に答える 2

72

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

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;

ルート/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
}

ルート/ブログ/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/アプリで使用するすべてのアルゴリズムを格納するフォルダーがあります。

これがより明確になることを願っています。この構造は、私が理解しやすいと思うので、私にとっては不思議に働いています。

于 2013-03-22T14:15:22.490 に答える
9

いくつかの違いはありますが、これが私が行っている方法のほとんどです。

  • db-layer の関数内にオープンリスナーを含めることはできないと思います。あなたのような永続的な接続を使用するときに私が通常行うことは、db open ハンドラーでアプリケーション自体を開始することです。永続的な接続を使用したくない場合は、db レイヤー関数で createConnection を使用し、コールバックを呼び出す前に閉じていることを確認してください。私は自分自身を明確にしているかどうかわかりません。コード例が必要な場合はお知らせください。
  • これはより一般的な node.js のヒントですが、データベース接続文字列とその他の構成を json ファイルに保持し、必要な場所でそれを要求します。その後、おそらく別の settings.js ファイルは必要ありません。
  • スキーマ関数 ( http://mongoosejs.com/docs/api.html#schema_Schema-method ) を使用して、一部のアプリ機能をモデル自体にコーディングすることもできます。
于 2013-03-22T05:47:14.487 に答える