【问题标题】:Mongoose models scheme in separate modul单独模块中的猫鼬模型模式
【发布时间】:2013-06-23 11:02:31
【问题描述】:

免责声明: 我是猫鼬/节点的新手,所以如果我误解了一些基本的东西,请原谅。 是的,我已经找到了a few postings 关于this topic,但无法适应我的需要。

我将我的主要项目分为多个单独的项目。一种分离是“app-core”项目,它将包含core-models和-modules,由其他项目注入(app-core在每个项目的package.json文件中配置为依赖项)。

app-core 中的(简化)模型目前如下所示:

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

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

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

wep-app 包含这个模型如下:

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 中配置的连接。 p>

由于封装和责任设计,我绝对不希望核心为每个可能的应用程序(可能包括核心应用程序)定义连接。 所以不知何故,我只需要在核心中指定方案。

我已经读到我不应该要求模型本身(/app-core/models/Industry),而是使用猫鼬模型

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

然后我得到错误

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

要解决这个问题,我应该手动注册模型,就像第一个链接中建议的那样(在我的帖子顶部)。但不知何故我不喜欢这种方法,因为每次应用程序使用新模型时我都需要扩展它。

此外,即使在核心应用程序中,我也需要一个 mongo 连接 - 至少要运行 mocha 测试。

所以我对在这种情况下如何构建架构有点困惑。

更新 #1

我现在找到了一种可行的解决方案。但是,不幸的是,这并不完全符合我的要求,因为通过钩子(即 TestSchema.pre('save'..))扩展模型非常困难(分别是丑陋的)。

模型(应用程序核心)

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

models.js(app-web,启动时执行一次)

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(网络应用)

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

那么我就可以得到一个模型如下

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

【问题讨论】:

    标签: node.js mongodb model mongoose


    【解决方案1】:

    为什么不尝试从 app-core 模块中导出 mongoose 实例,稍后在 web-app 中使用它来连接数据库

    app-core index.js

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

    网络应用 index.js

    var core = require('app-core'),
        mongoose = core.mongooseInstance,
    
    mongooseClient = mongoose.connect(DB_URL);
    // and so on
    

    只要您需要控制器中的模型,这些模型是在 index.js 中的代码之后初始化的,这可能会起作用。希望我的回答对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-04-24
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 2016-08-05
      • 2016-07-03
      相关资源
      最近更新 更多