使用嵌套模式引导 Mongoose 模型

Bootstrapping Mongoose models with nested schemas

你好,我在使用嵌套模式初始化我的 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); 
});

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

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);

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

有更好的方法吗?我错过了什么?

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

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

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

这看起来很老套。

这就是我避免使用 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 将从头开始加载你的模块。在此之后,它将 return 来自内部缓存的模块。