【发布时间】: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;
})();
这看起来非常hacky。
【问题讨论】: