2013-06-26 33 views
4

免責聲明: 我是新來的貓鼬/節點,所以請原諒我,如果我誤解了一些基本的東西。 是的,我發現已有a few postingsthis topic,但無法適應我的需要。貓鼬模型方案在單獨的模塊

我將我的主項目組織成多個獨立的項目。一個分離是「應用核心」項目,它將包含核心模型和模塊,由每個其他項目注入(app-core被配置爲每個項目的package.json文件的依賴關係)。

A(簡化的)應用程序核心內模型目前看起來像這樣:

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

var IndustrySchema = new Schema({ 
name: { 
    type: String, 
    required: true 
} 
}); 

module.exports = mongoose.model('Industry', IndustrySchema); 

的WEP-應用包含這種模式如下:

var Industry = require('app-core/models/Industry'); 

並創建這樣的MongoDB的連接:

var DB_URL = 'mongodb://localhost/hellowins'; 
var mongoose = require('mongoose'); 
var mongooseClient = mongoose.connect(DB_URL); 
mongooseClient.connection.on('connected',function() { 
    console.log("MongoDB is connected"); 
}); 

現在我有問題,該模型不會使用在app-web項目中定義的mongo連接,而是會考慮在app-core中配置的連接。

由於封裝和責任設計,我明確不希望核心定義每個可能的應用程序(可能包括核心應用程序)的連接。 所以不知何故,我只需要在覈心中指定該方案。

我看已經是我不應該要求模型本身(/應用核心/模型/工業),並用貓鼬模型代替

var Industry = mongoose.model("Industry"); 

但後來我得到的錯誤

MissingSchemaError: Schema hasn't been registered for model "Test" 

爲了解決這個問題,我應該手動註冊模型,比如在第一個鏈接(在我發佈的頂部)提供建議。但不知何故,我不喜歡這種方法,因爲每當應用程序使用新模型時,我都需要擴展它。

此外,即使在覈心應用程序中我也需要一個mongo連接 - 至少要運行摩卡測試。

所以我對這種情況下如何構建架構感到困惑。

更新#1

我現在一個可行的解決方案中。但是,不幸的是,這並不完全符合我的要求,因爲通過鉤子來擴展模型(例如TestSchema.pre('save'..))非常困難(或者很醜)。

模型(APP-芯)

exports.model = { 
    name: { 
     type: String, 
     required: true 
    } 
}; 

models.js(APP-幅材,在啓動時執行一次)

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 
var models = ['Test']; // add many 
exports.initialize = function() { 
    var l = models.length; 
    for (var i = 0; i < l; i++) { 
     var model = require('hw-core/models/' + models[i]); 
     var ModelSchema = new Schema(model.model); 
     module.exports = mongoose.model(models[i], ModelSchema); 
} 

};

app。JS(web應用)

require('./conf/app_models.js').initialize(); 

然後我就可以得到一個模型遵循

var mongoose = require('mongoose'); 
var TestModel = mongoose.model("Test"); 
var Test = new TestModel(); 

回答

0

你爲什麼不嘗試貓鼬例如,從您的應用程序內核模塊導出並在以後使用在web應用程序連接到數據庫

應用核心index.js

var mongoose = require('mongoose'); 
module.exports = { 
    mongooseInstance: mongoose }; 

web應用程序index.js

var core = require('app-core'), 
    mongoose = core.mongooseInstance, 

mongooseClient = mongoose.connect(DB_URL); 
// and so on 

只要你的控制器中需要你的模型,它是在index.js的代碼之後初始化的,我希望我的迴應有幫助。