如何在Mongoose中创build相互依赖的模式?

我有两个Schema,我希望他们与海誓山盟互动。 例如:

// calendar.js var mongoose = require('mongoose'); var Scema = mongoose.Schema; var Day = mongoose.model('Day'); var CalendarSchema = new Schema({ name: { type: String, required: true }, startYear: { type: Number, required: true } }); CalendarSchema.methods.getDays = function(cb){ Day.find({ cal: this._id }, cb); } module.exports = mongoose.model('Calendar', CalendarSchema); // day.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ObjectId = Schema.ObjectId; var Calendar = mongoose.model('Calendar'); var DaySchema = new Schema({ cal: { type: ObjectId, required: true }, date: { type: Number, required: true }, text: { type: String, default: 'hello' } }); DaySchema.methods.getCal = function(cb){ Calendar.findById(this.cal, cb); } module.exports = mongoose.model('Day', DaySchema); 

但是,我得到一个错误,因为每个架构依赖于另一个。 有没有办法让这个工作使用mongoose? 我包括他们这样的:

 // app.js require('./models/calendar'); require('./models/day'); 

我意识到这是一个古老的线索,但我确定发布解决scheme将帮助其他人。

解决scheme是在需要相互依赖的模式之前导出模块:

 // calendar.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var CalendarSchema = new Schema({ name: { type: String, required: true }, startYear: { type: Number, required: true } }); module.exports = mongoose.model('Calendar', CalendarSchema); // now you can include the other model and finish definining calendar var Day = mongoose.require('./day'); CalendarSchema.methods.getDays = function(cb){ Day.find({ cal: this._id }, cb); } // day.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ObjectId = Schema.ObjectId; var DaySchema = new Schema({ cal: { type: ObjectId, required: true }, date: { type: Number, required: true }, text: { type: String, default: 'hello' } }); module.exports = mongoose.model('Day', DaySchema); // same thing here. require after exporting var Calendar = require('./calendar'); DaySchema.methods.getCal = function(cb){ Calendar.findById(this.cal, cb); } 

这真的很简单。 Brian Bickerton的解释可以在这里find:

http://tauzero.roughdraft.io/3948969265a2a427cf83-requiring-interdependent-node-js-modules

能够在模块中使用名称function,而不是使用冗长的module.exports.name。 还有一个地方可以查看和查看要导出的所有内容。 通常,我所看到的解决scheme是通常定义函数和variables,然后将module.exports设置为包含所需属性的对象。 这在大多数情况下工作。 当两个模块相互依赖并且相互需要的时候,就会发生崩溃。 在最后设置出口导致意想不到的结果。 为了解决这个问题,只需在顶部指定module.exports,然后再需要其他模块。

你需要这些文件。 如果他们在同一条path上,请执行以下操作:

 //calendar.js var Day = require('./day'); /* Other logic here */ var CalendarSchema = new Schema({ name: { type: String, required: true }, startYear: { type: Number, required: true } }) , Calendar; /* other logic here */ /* Export calendar Schema */ mongoose.model('Calendar', CalendarSchema); Calendar = mongoose.model('Calendar'); exports = Calendar; 

在day.js做同样的事情

编辑:JohnnyHK说这不起作用。 链接到解释