【问题标题】:Bootstrapping Mongoose models with nested schemas使用嵌套模式引导 Mongoose 模型
【发布时间】:2015-03-29 06:06:04
【问题描述】:

您好,我在使用嵌套模式初始化 Mongoose 模型时遇到问题,您知道,这是我的服务器。

var express = require('express'),
  mongoose = require('mongoose');
  bootstrap = require('./lib/bootstrap.js');

var app = express();

// Connect to Mongo when the app initializes
mongoose.connect('dir');

// Config should go here
bootstrap.execute();

// Setting up the app
app.use('/events', require('./route/events.js'));

var server = app.listen(process.env.PORT || 5000, function() { 
  console.log('Listening on port %d', server.address().port); 
});

我现在这样做的方式是使用引导函数:

module.exports = {

  execute: function() {

    // Bootstrap entities
    var entityFiles = fs.readdirSync("model");
    entityFiles.forEach(function(file) {
      require("../model" + file);
    }));

  }

}

但顺序很重要,因为我的架构有点像这两个:

var Presentation = mongoose.model('Presentation'),

var eventSchema = new Schema({
  ...
  presentations: [Presentation.schema]
});

module.export = mongoose.model('Event', eventSchema);

var presentationSchema = new Schema({
  ...
  dateTime: Date
});

module.exports = mongoose.model('Presentation', presentationSchema);

如您所见,它们相互依赖,而这只是其中的两个。所以这意味着有些人会比其他人先被引导,无疑会抛出错误。

有没有更好的方法来做到这一点?我错过了什么?

我想在需要它们时只使用模式而不是模型,但是我必须将我的模式文件更改为如下内容:

var presentationSchema = new Schema({
    ...
    dateTime: Date
});

module.exports = (function() {
    mongoose.model('Presentation', presentationSchema);
    return presentationSchema;
})();

这看起来非常h​​acky。

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    这就是我避免使用 mongoose.model 加载模型的原因。

    相反,如果您只是在需要时需要该模型,它将按预期工作:

    var Presentation = require('./presentation');
    
    var eventSchema = new Schema({
       ...
       presentations: [Presentation.schema]
    });
    
    module.export = mongoose.model('Event', eventSchema);
    

    记住 Node.js cache its modules,所以当你第一次调用 require 时,node 会从头开始加载你的模块。之后,它会从内部缓存中返回模块。

    【讨论】:

    • 另外一个说明,为什么需要时使用“./x”而不是“x”?
    • 因为如果您需要“x”,它将查看“node_modules”路径,而不是当前脚本的路径。你可以在这里寻找更好的本地需求策略:gist.github.com/branneman/8048520
    猜你喜欢
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 2015-03-10
    相关资源
    最近更新 更多