0

まず、NoSQL & node.js でこれを行っています。それは質問に影響を与えるべきではないと思いますが、私の例を理解するのに役立ちます。

次のようなページとタグのモデルがあります。

var Page = app.ormDb.define('pages', {
    uuid            : { type: String, index: true, length: 40, default: function () { return uuid.v4(); } },
    title           : { type: String, index: true, length: 255 },
    url             : { type: String, index: true, length: 255 },
    summary_mu      : { type: String, length: 1024 },
    summary_html    : { type: String },
    summary_hist    : { type: JSON, default: function() { rerutn { items : [] }; } },
    sections        : { type: JSON, default: function() { rerutn { items : [] }; } },
    tags            : { type: JSON, default: function() { rerutn { items : [] }; } },
    date            : { type: Date, default: function() { return new Date(); } },
    updated         : { type: Date, default: function() { return new Date(); } }
});

var Tag = app.ormDb.define('tags', {
    uuid        : { type: String, index: true, length: 40, default: function () { return uuid.v4(); } },
    name        : { type: String, index: true, length: 255 },
    url         : { type: String, index: true, length: 255 },
    desc        : { type: String, length: 1024 },
    date        : { type: Date, default: function() { return new Date(); } },
    updated     : { type: Date, default: function() { return new Date(); } }
});

たとえば、ページにタグを追加するときは、タグ エントリがあることを確認する必要があります。この目的のために、モデルにメソッドを作成しました。

// Add a tag to a page
//   tag .. The tag to add
Page.prototype.addTag(tag, done) {
    var _this = this;
    if (_this.tags == null) {
        _this.tags = { items:[] };
    }

    var index = _this.tags.items.indexOf(tag);
    if (index == -1) {
        _this.tags.items.push(tag);
    }

    async.waterfall([
        function (cb) {
            app.models.tag.count({'name': tag}, cb);
        },
        function (count, cb) {
            if (count == 0) {
                app.models.tag.create({
                    name : tag,
                }, function (err, newTag) {
                    return cb(err, tag);
                });
            } else {
                return cb(null, tag);
            }
        }
    ], function (err, items) {
        done(err, items);
    });
}

コントローラーには、ユーザー入力を検証し、現在のページを読み込み、上記の Page メソッドを呼び出してタグを追加し、最後に更新されたページを保存するコードがあります。上記のメソッドでは、Tag コレクションでタグの存在を確認し、必要に応じて作成していることに注意してください。

これは正しいですか、それとも Page メソッドのロジックをコントローラーに移動し、モデルは 1 つのモデルのみを処理し、他のモデルは処理しないようにする必要がありますか?

私の理由は、Tag コレクションでタグを確認/作成せずにページにタグを追加することは決してないということです。

4

0 に答える 0