How to create interdependent schemas in Mongoose? How to create interdependent schemas in Mongoose? mongoose mongoose

How to create interdependent schemas in Mongoose?


I realize this is an ancient thread, but I'm sure posting the solution will help others down the road.

The solution is to export the module before requiring the interdependent schemas:

// calendar.jsvar 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 calendarvar Day = mongoose.require('./day');    CalendarSchema.methods.getDays = function(cb){   Day.find({ cal: this._id }, cb);}// day.jsvar 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 exportingvar Calendar = require('./calendar'); DaySchema.methods.getCal = function(cb){   Calendar.findById(this.cal, cb);}

It really is that simple. Explanation by Brian Bickerton can be found here:

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

It's nice to be able to use functions by name within a module instead of the lengthy module.exports.name. It's also nice to have a single place to look and see everything to be exported. Typically, the solution I've seen is to define functions and variables normally and then set module.exports to an object containing the desired properties at the end. This works in most cases. Where it breaks down is when two modules are inter-dependent and require each other. Setting the exports at the end leads to unexpected results. To get around this problem, simply assign module.exports at the top, before requiring the other module.


You need require the files. If they are in the same path do this:

//calendar.jsvar 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;

Do the same in day.js

EDIT: As JohnnyHK says this don`t work. Link to explanation